linux – 关闭不需要的文件描述符

我想了解管道是如何工作的.此代码段来自某个网​​站.

所以我对该程序的理解如下:

当我们做管道(fd)然后fd [0] = 3并且fd [0] = 4(假设到现在只有0,1& 2打开).现在我们分叉父,然后如果没有创建子,那么我们就会出错并退出.

但是如果它成功创建了子文件,文件描述符是否复制到子文件中,我的意思是fd [0] = 3和fd [1] = 4对于子进程也是如此? fd [0]和fd [1]是文件句柄(我们没有具体指定)?

让我们假设我们希望孩子从父母那里读取,父母应该关闭fd [0]而孩子应该关闭fd [1],但为什么呢?如果我们不关闭它们会发生什么?
我不理解在技术说明中,如果管道的不必要的末端没有明确关闭,EOF将永远不会被返回. .

If the parent wants to receive data from the child, it should close
fd1, and the child should close fd0. If the parent wants to send data
to the child, it should close fd0, and the child should close fd1.
Since descriptors are shared between the parent and child, we should
always be sure to close the end of pipe we aren’t concerned with. On a
technical note, the EOF will never be returned if the unnecessary ends
of the pipe are not explicitly closed.

    #include <stdio.h>
    #include <unistd.h>
    #include <sys/types.h>

    main()
    {
            int     fd[2];
            pid_t   childpid;

            pipe(fd);

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

            if(childpid == 0)
            {
                    /* Child process closes up input side of pipe */
                    close(fd[0]);
            }
            else
            {
                    /* Parent process closes up output side of pipe */
                    close(fd[1]);
            }
            .
            .
    }

解决方法:

fork实际上是一个fork.您获得两个几乎相同的过程.主要区别在于fork()系统调用的返回值,它是被识别为父项的子项的pid和子项中的0(这是软件如何确定哪个进程被视为父项(父母有责任照顾孩子,孩子是谁.

特别是,内存是重复的,因此fd数组将包含相同的内容(如果fd [0]在一个进程中为3,在另一个进程中将为3)并且文件描述符是重复的.子节点中的fd 3将指向与父节点中的fd 3相同的打开文件描述.

因此,父和子的fd 3将指向管道的一端,父和子的fd 4(fd [1])将指向另一端.

您希望将该管道用于一个进程以将数据发送到另一个进程.通常,其中一个进程将写入fd 4,另一个进程将从fd 3读取,直到它看到文件结束.

当关闭管道另一侧的所有fds时,到达文件的末尾.因此,如果读者没有将其fd关闭到另一侧,它将永远不会看到文件的结尾.

类似地,如果读者死亡,作者将永远不会知道如果它没有将自己的fd关闭到管道的另一侧,它必须停止写入.

上一篇:案例十二、shell多线程备份数据库


下一篇:python – 在linux中通过命名管道发送数据块