小编Jon*_*yen的帖子

读取直到管道关闭

我现在正在做作业以介绍操作系统,我玩得很开心,但同时也很困惑。我现在正在做管道工作;我的代码如下。

最初,我的代码如下所示:

// Child process - write
if (fork() == 0) {
    fprintf(stderr, "Child\r\n");
    close(1);
    dup(p[1]);
    close(p[0]);
    close(p[1]);
    runcmd(pcmd->left);
// Parent process - read
} else {
    wait(0);
    close(0);
    dup(p[0]);
    close(p[0]);
    close(p[1]);
    fprintf(stderr, "Parent\r\n");
    runcmd(pcmd->right);
}
Run Code Online (Sandbox Code Playgroud)

我对此的思考过程是,父母会等到孩子被终止,然后从管道中读取,就是这样。我在我们的讨论页面上将此代码发布给了我的导师,他告诉我代码存在几个问题,其中之一是:

  1. 如果子进程运行足够长的输入以阻塞管道,则父进程可能会无限挂起。

He mentioned that the correct implementation therefore (in regards to wc), would be to use a blocking read command, which would wait on the pipe until data was available, and then begin reading until the pipe has closed.

I tried looking …

pipe

7
推荐指数
1
解决办法
1万
查看次数

标签 统计

pipe ×1