简体   繁体   English

是否有必要封闭父母子女中管道的相对两端?

[英]Is it necessary to close the opposite ends of a pipe in parent and child?

The following is a general pipe() usage example: 以下是一般 pipe() 用法示例:

int fd[2];
pipe(fd);

if((childpid = fork()) == -1)
{
        perror("fork");
        exit(1);
}

if(childpid == 0)
{
        /* Child process closes up input side of pipe */
        close(fd[0]);

        ////.....some code....////
        exit(0);
}
else
{
        /* Parent process closes up output side of pipe */
        close(fd[1]);

        ////.....some code....////
}

What I want to know is that whether the call to close(fd[0]) in the child and close(fd[1]) in the parent process is necessary . 我想知道的是, 是否调用 close(fd[0])在孩子和close(fd[1])的父进程是必要的

What happens if I don't close() them and use only fd[1] in the child and fd[0] in the parent. 如果我不 close()它们,只在子级中使用fd[1] ,在父级中使用fd[0]会发生什么情况

Is it closed just so that we accidentally don't do something with those descriptors? 它是封闭的只是为了使我们不小心对这些描述符不做任何事情吗?

如果两个进程的两端都打开了,如果一个进程死了,那么另一个进程将死锁,而不是在读取时检测到EOF(因为仍然有一个writer:本身),或者在写入时被SIGPIPE杀死(因为仍然有一个读取器):本身)。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM