pipe() 从 1 个父进程到单独的 c 文件中的多个子进程
pipe() from 1 parent to multiple child processes in separate c file
我有一个使用 fork()
创建多个子进程的程序。该程序从 parent.c 的主体开始。 fork后父进程调用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 做什么?
子进程需要将管道 FD 传递给 execl
编辑的程序。最简单的方法是使用 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);
}
子程序需要使用atoi
或strtoul
将argv[1]
转换为整数,然后将其用作输入FD。
我有一个使用 fork()
创建多个子进程的程序。该程序从 parent.c 的主体开始。 fork后父进程调用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 做什么?
子进程需要将管道 FD 传递给 execl
编辑的程序。最简单的方法是使用 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);
}
子程序需要使用atoi
或strtoul
将argv[1]
转换为整数,然后将其用作输入FD。