2012-01-20 82 views
0

可以/正確地做到這一點嗎?如果我從「子」進程的fd1 [1]寫入,那麼可以從「父」進程的fd2 [0]中讀取數據?叉後創建管道

main(){ 
    pid_t pid; 
    pid = fork(); 
    if(pid <0){ 
     return -1; 
    } 
    if(pid == 0){ 
     int fd1[2]; 
     int fd2[2]; 
     pipe(fd1); 
     pipe(fd2); 
     close fd1[1]; 
     close fd2[0]; 
     //writes & reads between the fd1 pipes 
     //writes & reads between the fd2 pipes 
    }else{ 
     int fd1[2]; 
     int fd2[2]; 
     pipe(fd1); 
     pipe(fd2); 
     close fd1[1]; 
     close fd2[0]; 
     //writes & reads between the fd1 pipes 
     //writes & reads between the fd2 pipes 
    } 
} 
+3

那麼你的問題是什麼?我看起來不像你無法測試自己的東西。 – Tudor

回答

4

沒有,使用的進程間通信管道應創建fork()(否則,你有沒有簡單的方法來發送直通他們,因爲閱讀和寫作兩端應通過不同的工藝中使用) 。

有骯髒的把戲發送流程之間的文件描述符帶外消息的插座上,但我真的忘了細節,這是醜陋的

3

您分叉前需要設置管道

int fds[2]; 

if (pipe(fds)) 
    perror("pipe"); 

switch(fork()) { 
case -1: 
    perror("fork"); 
    break; 
case 0: 
    if (close(fds[0])) /* Close read. */ 
     perror("close"); 

    /* What you write(2) to fds[1] will end up in the parent in fds[0]. */ 

    break; 
default: 
    if (close(fds[1])) /* Close write. */ 
     perror("close"); 

    /* The parent can read from fds[0]. */ 

    break; 
}