【问题标题】:pipe() from 1 parent to multiple child processes in separate c filepipe() 在单独的 c 文件中从 1 个父进程到多个子进程
【发布时间】:2015-03-17 05:48:26
【问题描述】:

我有一个使用fork() 创建多个子进程的程序。该程序在 parent.c 的 main 中启动。分叉后,父进程调用excel 执行child.c。我究竟如何在两个不同的程序之间共享管道。我知道我必须在 parent.c 中为每个子进程创建一个管道,如下所示:

int myPipe[nChildren][2];
int i;

for (i = 0; i < nChildren; i++) {
    if (pipe(myPipe[i]) == -1) {
        perror("pipe error\n");
        exit(1);
    }
    close(pipe[i][0]); // parent does not need to read
}

但是我需要在 child.c 中做什么?

【问题讨论】:

    标签: c unix process pipe fork


    【解决方案1】:

    子进程需要将管道FD传递给execl'ed程序。最简单的方法是使用dup2 将管道移动到FD 0 (stdin)。 例如:

    pid = fork();
    if (pid == 0) {
      // in child
      dup2(pipe[i][0], 0);
      execl(...);
    }
    

    或者,您可以在 child.c 中使用命令行参数来接受管道的 FD 编号。例如:

    pid = fork();
    if (pid == 0) {
      // in child
      sprintf(pipenum, "%d", pipe[i][0]);
      execl("child", "child", pipenum, (char *) NULL);
    }
    

    子程序需要使用atoistrtoulargv[1] 转换为整数,然后将其用作输入FD。

    【讨论】:

    • 我不允许使用dup2。你能举一个传递FD号码的例子吗?谢谢
    • 但是我不允许使用dup2.,因为孩子只需要阅读,我是否只需将pipe[0]作为命令行参数传递?
    猜你喜欢
    • 2017-06-29
    • 2014-05-11
    • 1970-01-01
    • 1970-01-01
    • 2016-07-27
    • 1970-01-01
    • 2017-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多