Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/55.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在单独的c文件中将()从一个父进程传递到多个子进程_C_Unix_Process_Pipe_Fork - Fatal编程技术网

在单独的c文件中将()从一个父进程传递到多个子进程

在单独的c文件中将()从一个父进程传递到多个子进程,c,unix,process,pipe,fork,C,Unix,Process,Pipe,Fork,我有一个使用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

我有一个使用
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
}
int-myPipe[nChildren][2];
int i;
对于(i=0;i

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

子进程需要将管道FD与执行程序进行通信。最简单的方法是使用
dup2
将管道移动到FD 0(
stdin
)。 例如:

pid = fork();
if (pid == 0) {
  // in child
  dup2(pipe[i][0], 0);
  execl(...);
}
pid = fork();
if (pid == 0) {
  // in child
  sprintf(pipenum, "%d", pipe[i][0]);
  execl("child", "child", pipenum, (char *) NULL);
}
或者,您可以使用child.c中的命令行参数来接受管道的FD编号。例如:

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

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

我不允许使用
dup2
。你能举一个传递FD号码的例子吗?谢谢,但我不允许使用
dup2。
因为孩子只需要阅读,我是否只传递
pipe[0]
作为命令行参数?