叉和管道实施++编译 [英] forks and pipes implementation linux compiler

查看:133
本文介绍了叉和管道实施++编译的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从管道采取了以下code Beej指南部分于Unix IPC 。

I have the following code taken from the "Pipes" section of Beej’s Guide to Unix IPC.

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(void)
{
    int pfds[2];

    pipe(pfds);

    if (!fork()) {
        close(1);       /* close normal stdout */
        dup(pfds[1]);   /* make stdout same as pfds[1] */
        close(pfds[0]); /* we don't need this */
        execlp("ls", "ls", NULL);
    } else {
        close(0);       /* close normal stdin */
        dup(pfds[0]);   /* make stdin same as pfds[0] */
        close(pfds[1]); /* we don't need this */
        execlp("wc", "wc", "-l", NULL);
    }

    return 0;
}

这code可让用户看到多少个文件是在一个特定的目录中。我怎么可以编辑该code来实现较长的管道猫/ etc / passwd文件|切-f1 -d:|排序?没有人有任何想法如何,因为我完全被卡住做到这一点。任何帮助将是AP preciated。

This code allows the user to see how many files are in a specific directory. How can I edit this code to implement the longer pipeline cat /etc/passwd | cut –f1 –d: | sort? Does anyone have any idea how to do this because I am completely stuck. Any help would be appreciated.

推荐答案

您需要(取决于命令列表的长度)一些管道。但是:在最大需要不超过两个管成对FDS为在中间过程中,对于第一个和最后需要一个管-成对FDS。真的一定要关闭这些不需要管FDS - 如果没有,子进程可能无法得到一个EOF和写不完

You need (depending on the length of the command list) some pipes. But: at maximum you need not more than two pipe-pair-fds for a process in the middle, for the first and the last you need one pipe-pair-fds. Be really sure to close the pipe-fds which are not needed - if not, the child processes might not get an EOF and never finish.

和(如user3392484说明):检查所有的系统调用错误情况,并报告给调用者。这会让生活变得更轻松。

And (as user3392484 stated): check all system calls for error conditions and report them to the caller. This will make life much easier.

我在最后的日子里实现这样的事情,也许你想看看有:的 pipexec.c

I implemented something like this during the last days, maybe you want to have a look there: pipexec.c.

亲切的问候 - 安德烈亚斯

Kind regards - Andreas

这篇关于叉和管道实施++编译的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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