【发布时间】:2013-05-06 18:42:40
【问题描述】:
我正在尝试通过管道将字符串列表传递给子进程,它应该使用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()。 -
Tnanks,这是真的!
-
我之前有它工作......不知道我做了什么,现在它根本不工作 - 这就是为什么你应该使用 VCS(版本控制系统)来管理代码。当某些东西运行得很好时,您可以保存一个版本,以便您有一个记录,如果您以后再次搞砸,您可以返回到该记录。即使在类的玩具程序中,在开发过程中使用 VCS 也有好处。 (我在
git存储库中保留了很多我的 SO 答案,如果我需要解决问题中的一些棘手问题,我会创建一个分支,复制并保存原始代码,然后开始处理我的答案。 ) -
另见 C system calls
pipe(),fork()andexec()— 相同的 OP。也与How to loop through stdin pipe output to a child —execl()command in C 非常相似——不同的OP。