在单独的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]
作为命令行参数?