我对 C 很陌生,不确定如何继续。
使用此代码,我试图创建多个子进程,这些子进程会将它们的标准输出发送到它们的父标准输入,并且可以使用数组中指针位置的 fdprintf 写入它们的标准输入。
当使用读取标准输入并打印到其标准输出(应通过管道返回)的基本程序执行时,该代码似乎不起作用。(在主代码的不同部分中,我 fprintf 到管道开始的位置,然后读取 stdin 等待应该写回的内容)。
int plumber(int *pipes[], int numChildren, char* command[]) {
int i;
char id;
int nullSpace = open("/dev/null", O_WRONLY);
for(i = 0; i < numChildren; ++i) {
id = 'A' + i;
pipe(pipes[2 * i]);
pipe(pipes[2 * i + 1]);
switch(fork()) {
case (-1):
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
break;
case 0:
//child
//close child's write, dupe its stdin to read
//close childs old read
close(pipes[2 * i][1]);
if(dup2(pipes[2 * i][0], 0) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(pipes[2 * i][0]);
//close child's read, dupe its stdout to write
//close childs old write
close(pipes[2 * i + 1][0]);
if(dup2(pipes[2 * i + 1][1], 1) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(pipes[2 * i + 1][1]);
close(1);
//child stderr to nullspace
if(dup2(nullSpace, 2) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(2);
execlp(command[i], "childprocess", numChildren, id, NULL);
break;
default:
//parent
//close read pipe from writing pipe
close(pipes[2 * i][0]);
//close write pipes and dupe stdin to read
//close parents old read
close(pipes[2 * i + 1][1]);
if(dup2(pipes[2 * i + 1][0], 0) == -1) {
fprintf(stderr, "Unable to start subprocess\n");
exit(4);
}
close(pipes[2 * i + 1][0]);
}
}
close(nullSpace);
return 0;
}
该命令只是运行子进程,它还获取子进程的数量和从 A 到 D 的 id。*pipes[] 是 numChildren*2 乘以 2(因此沿着其子 1 读取管道,child1 写入管道,child2 读取,child2 写等。请提前帮助和感谢。