2012-11-22 48 views
1

我有一个父母和一个孩子prozess,并希望通过管道从父母写一个EOF到孩子......这是如何工作的?写一个EOF到管道

这里是我的attampt:

---父代码---

if(dup2(parent_pipe[1], STDOUT_FILENO) == -1) { /*stdout gets closed and parent_pipe is duplicated with id of stdout*/ 
     error("Can't duplicate the write-end of the pipe to stdout!"); 
} 
if(close(parent_pipe[0]) == -1) { 
    error("Can't close read-end of the pipe!"); 
} 

char blub[] = "EOF"; 
if(write(parent_pipe[1], blub, strlen(blub)) == -1) { 
error("Failed to write the array"); 
} 

---孩子码---

if(dup2(parent_pipe[0], STDIN_FILENO) == -1) { /*stdin gets closed and parent_pipe is duplicated with id of stin*/ 
    error("Can't duplicate the read-end of the pipe to stdin!"); 
} 
/* close the write-end of the pipe */ 
if(close(parent_pipe[1]) == -1) { 
    error("Can't close write-end of the pipe"); 
} 

while(fgets(readbuffer, ROWLENGTH, stdin) != NULL) { 
    printf("Received string: %s", readbuffer, nbytes); 
} 

孩子等待和EOF不停止,我该如何解决这个问题? 由于事先

+1

'如果(写(parent_pipe [1],泡壳,1 + strlen的(泡壳) )== -1){'请注意,blub []没有'\ n',因此fgets将阻塞,直到管道实际上关闭。 – wildplasser

回答

4

当你想停止通信,则必须在父进程关闭管道:

dup2(...); 
... 
write to child 
... 
close(parent_pipe[1]); 
+0

是的,我想停止沟通..它的工作: (void)close(parent_pipe [1]); (void)close(STDOUT_FILENO); 多数民众赞成真棒谢谢这么多:) – krixikraxi