Why do I need to close fds when reading and writing to the pipe?

后端 未结 5 810
迷失自我
迷失自我 2020-12-24 09:28

Here is an example to illustrate what I mean:

#include 
#include 
#include 

int main(void)
{
        int           


        
5条回答
  •  鱼传尺愫
    2020-12-24 09:45

    After performing the fork, all fds are duplicated. Each process has both ends of the pipe open. If you only want to use one end you should close the other (if your process writes, close the read end).

    Besides the obvious fact that if you do not close the descriptors the OS will keep extra entries in the open file table, if you do not close the write end of the pipe, the reader will never receive EOF since there is still a way of entering data into the pipe. AFAIK (and IIRC) there is no problem in not closing the read fd in the other process --that is, besides the file being open for no reason.

    It is also recommended (as good practice, not that it affects too much) that you close all descriptors before exiting the application (that is, closing the other end of the pipe after the read/write operation is completed in each process)

提交回复
热议问题