加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – 为什么在阅读和写入管道时需要关闭fds?

发布时间:2020-12-16 05:42:47 所属栏目:百科 来源:网络整理
导读:这是一个 example来说明我的意思: #include stdio.h#include unistd.h#include sys/types.hint main(void){ int fd[2],nbytes; pid_t childpid; char string[] = "Hello,world!n"; char readbuffer[80]; pipe(fd); if((childpid = fork()) == -1) { perror
这是一个 example来说明我的意思:
#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);

}

但是,如果我的一个进程需要持续写入管道,而另一个管道需要读取呢?

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

解决方法

您的管道是一个单向指示流,每一端都有一个文件描述符.关闭()管道的任何一端以允许数据传递,这不是必需的.

如果您的管道跨越进程(即在fork()之前创建,然后父子使用它进行通信),则可以有一个写入和一个读取结束.那么最好关闭管道的不想要的末端.这会

>确保当写入端关闭管道时,读端可以看到.举个例子,说孩子是写字面,死了.如果父写方面尚未关闭,则父管理员将不会从管道获取“eof”(零长度read()) – 因为管道具有打开的写入端.
明确哪个过程正在做写作,哪个过程正在读取管道.

如果您的管道跨越线程(在同一过程中),则不要关闭管道的不需要的末端.这是因为文件描述符由进程保存,并且为一个线程关闭它将关闭所有线程,因此管道将变得不可用.

没有任何东西阻止你有一个过程不断地写入管道和其他过程阅读.如果这是一个问题,那么你可以给我们更多的细节来帮助你.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读