我使用管道在父进程和子进程之间进行通信。我读的书说,在父进程中,我必须关闭 pipefd [1],但我没有这样做,没有其他任何事情发生,所以我的问题是“如果我不关闭 pipefd [1],有什么不受控制?” 此致!
int pipefd[2];
if(pipe(pipefd) == -1)
{
perror("pipe communication error");
exit(EXIT_FAILURE);
}
int fd = fork();
if(fd < 0)
{
perror("fork child process error");
exit(EXIT_FAILURE);
}
if(fd != 0)//run in parent proc
{
int a = -1;
int i = 1;
//close(pipefd[1]); ## here! ##
while(i)
{
read(pipefd[0], &a, sizeof(a));
printf("%d\n", a);
sleep(4);
}
}
else//run in child proc
{
int i = 1;
//close(pipefd[0]); ## here! ##
while(i)
{
write(pipefd[1], &i, sizeof(i));
i++;
sleep(1);
}
}