gpt4 book ai didi

C 管道、fork、dup 和 exec()

转载 作者:行者123 更新时间:2023-12-02 02:02:34 25 4
gpt4 key购买 nike

我试图通过管道将字符串列表传递给子进程,它应该通过 /bin/cat 显示使用 execl() .我早些时候让它工作,只是管道没有关闭所以程序一直在等待。不知道我做了什么,现在它根本不起作用。有人可以看到我的代码并告诉我我做错了什么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);
}

最佳答案

您可能想添加该行

catPID = fork();

我不知道为什么你有 pipe(fds)两次

关于C 管道、fork、dup 和 exec(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16510069/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com