gpt4 book ai didi

c - 通过管道连接两个子进程,一个用于 ls,另一个用于 sort,但 sort 不起作用

转载 作者:行者123 更新时间:2023-11-30 15:09:36 26 4
gpt4 key购买 nike

我正在尝试创建两个子进程并通过管道传输它们,但第二个子进程没有对第一个执行 ls 的子进程产生的输出进行排序。我做错了什么?

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>

int main(int argc, char *argv[]) {
int pipefd[2];
pid_t ls_pid, wc_pid;

pipe(pipefd);

if ((ls_pid = fork()) == 0) {

dup2(pipefd[1],STDOUT_FILENO);
close(pipefd[0]);

execl("/bin/ls", "ls", 0);
perror("exec ls failed");
exit(EXIT_FAILURE);
}


if ((wc_pid = fork()) == 0) {

dup2(pipefd[0], STDIN_FILENO);

close(pipefd[1]);
execl("/usr/bin/sort", "sort", NULL);
perror("exec wc failed");
exit(EXIT_FAILURE);
}


return EXIT_SUCCESS;
}

最佳答案

排序应该可以工作,但是代码中有两个注意事项,首先,确保在所有保存对 fd 的引用的进程中关闭 fd,否则 fd 将不会关闭,这就是排序进程挂起的原因完成后,因为它没有从 stdin 接收到 EOF,那是因为父进程中的 pipelinefd 没有关闭。另一种是确保等待 children 退出并检查他们的退出状态。在 main 函数的 send 中添加以下内容:

close(pipefd[0]);
close(pipefd[1]);

int status;
int pid = waitpid(ls_pid, &status, 0);
pid = waitpid(wc_pid, &status, 0);

关于c - 通过管道连接两个子进程,一个用于 ls,另一个用于 sort,但 sort 不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36585896/

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