为什么在读写管道时需要关闭fds? [英] Why do I need to close fds when reading and writing to the pipe?

查看:225
本文介绍了为什么在读写管道时需要关闭fds?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个示例,用于说明我的意思:

Here is an example to illustrate what I mean:

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

int main(void)
{
        int     fd[2], nbytes;
        pid_t   childpid;
        char    string[] = "Hello, world!\n";
        char    readbuffer[80];

        pipe(fd);

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

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

                /* Send "string" through the output side of pipe */
                write(fd[1], string, (strlen(string)+1));
            exit(0);
    }
    else
    {
            /* Parent process closes up output side of pipe */
            close(fd[1]);

            /* Read in a string from the pipe */
            nbytes = read(fd[0], readbuffer, sizeof(readbuffer));
            printf("Received string: %s", readbuffer);
    }

   return(0);

}

但是,如果我的一个进程需要连续写入管道而另一个管道需要读取该怎么办?

However, what if one of my processes needs to continuously write to the pipe while the other pipe needs to read?

上面的示例似乎只适用于一次写入和一次读取.

The example above seems to work only for one write and one read.

推荐答案

您的管道是单向流-每个端点都有一个文件描述符.不必在管道的任一端都关闭()来允许数据通过.

Your pipe is a unidirectional stream - with a file descriptor for each end. It is not necessary to close() either end of the pipe to allow data to pass along it.

如果您的管道跨越进程(即在fork()之前创建,然后父级和子级使用它进行通信),则可以写一次,读一次结束.然后,优良作法是关闭管道不需要的端部.这将

if your pipe spans processes (i.e. is created before a fork() and then the parent and child use it to communicate) you can have one write and and one read end. Then it is good practice to close the unwanted ends of the pipe. This will

  • 确保在写入端关闭管道时,读取端可以看到它.举个例子,假设孩子是写方,它就死了.如果父级写端尚未关闭,则父级不会从管道中获取"eof"(零长度read())-因为管道具有开放的写端.
  • 弄清楚是哪个进程在写管道,哪个进程在读管道.

如果您的管道跨螺纹(在同一过程中),请不要关闭管道的多余端头.这是因为文件描述符由进程保留,并且关闭一个线程的文件描述符将关闭所有线程的文件描述符,因此管道将变得不可用.

if your pipe spans threads (within the same process), then do not close the unwanted ends of the pipe. This is because the file descriptor is held by the process, and closing it for one thread will close it for all threads, and therefore the pipe will become unusable.

没有什么可以阻止您使一个进程连续写入管道,而另一个进程连续读取.如果您遇到问题,请向我们提供更多详细信息,以帮助您.

There is nothing stopping you having one process writing continuously to the pipe and the other process reading. If this is a problem you are having then give us more details to help you out.

这篇关于为什么在读写管道时需要关闭fds?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆