我尝试通过管道传递字符串列表到子进程,它应该使用/bin/cat
通过execl()
显示。我之前有工作,除了管道没有关闭所以程序一直在等待。不知道我做了什么,现在根本不工作。有人可以看到我的代码,并告诉我,我在做错了,在子进程中cat没有显示str
数据吗?
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);
}
答案 0 :(得分:2)
您可能想要添加一行
catPID = fork();
而且我不确定为什么你有pipe(fds)
两次