我正在尝试通过管道将字符串列表传递给子进程,在那里它应该使用execl()
通过/bin/cat
显示。之前它已经能够工作了,除了管道没有关闭,所以程序一直在等待状态。现在不知道出了什么问题,完全不能工作。有人可以看看我的代码并告诉我我做错了什么,导致str
数据没有被子进程的cat
显示吗?
int main(int argc, char** argv) {
char *str[] = {"The", "quick", "brown", "fox", "jumped", "over", "the", "lazy", "dog"};
int fds[TOTAL_CHILDREN];
int writeFds;
int catPID;
int status;
FILE * write_to_child;
//create pipe
if (pipe(fds) == -1) {
perror("creating pipe: failed");
exit(EXIT_FAILURE);
}
pipe(fds);
//create subprocess for cat child
switch (catPID) {
case 0: // successful creation of child
close(fds[1]); //close write side from parents
close(0); //close stdin
dup(fds[0]); //connect pipe from execl cat to stdin
execl("/bin/cat", "cat", (char *) 0);
perror("exec failed!");
exit(20);
break;
case -1: //failure
perror("fork failed: cat process");
exit(EXIT_FAILURE);
default: //parent process
close(fds[0]);
writeFds = fds[1];
write_to_child = fdopen(fds[1], "w");
if (write_to_child == NULL) {
perror("write to pipe failed");
exit(EXIT_FAILURE);
}
break;
}
int i;
for (i = 0; i < 9; i++){
fprintf(write_to_child, "%s\n", str[i]);
}
fclose(write_to_child);
close(writeFds);
wait(&status);
return (EXIT_SUCCESS);
}
fork()
的问题,那么你应该在程序中调用fork()
。 - Barmargit
存储库中,如果我需要处理一个棘手的问题,我会创建一个分支,复制并保存原始代码,然后开始我的答案。) - Jonathan Lefflerpipe()
、fork()
和exec()
- 同一作者。也与如何循环遍历stdin管道输出到子进程 -execl()
命令在C中非常相似 - 不同的作者。 - Jonathan Leffler