gpt4 book ai didi

c - 程序卡在管道上(exec ls grep sort)

转载 作者:太空狗 更新时间:2023-10-29 12:02:16 25 4
gpt4 key购买 nike

我正在尝试制作一个程序来执行以下命令,使用管道将一个输出连接到下一个输入,并采用两个参数 DIR(目录)和 ARG(文件类型,例如:jpg)。

ls DIR -laR | grep ARG | |排序

代码如下:

int main(int argc, char *argv[]) {

if (argc != 3) {
printf("Invalid arguments. <dir> <arg>\n");
exit(1);
}

int pipe_fd1[2];
int pipe_fd2[2];
pid_t ls_pid, grep_pid;
int status;

pipe(pipe_fd1);
pipe(pipe_fd2);

ls_pid = fork();
if (ls_pid == 0) { //first child ls DIR -laR
dup2(pipe_fd1[1], STDOUT_FILENO);
close(pipe_fd1[0]);

execlp("ls", "ls", argv[1], "-laR", NULL);

} else if (ls_pid > 0) {
grep_pid = fork();
if (grep_pid == 0) { //second child grep ARG
dup2(pipe_fd1[0], STDIN_FILENO);
dup2(pipe_fd2[1], STDOUT_FILENO);
close(pipe_fd1[1]);
close(pipe_fd2[0]);

waitpid(ls_pid, &status, 0);
execlp("grep", "grep", argv[2], NULL);

} else if (grep_pid > 0) { //parent sort
dup2(pipe_fd2[0], STDIN_FILENO);
close(pipe_fd2[1]);

waitpid(grep_pid, &status, 0);
execlp("sort", "sort", NULL);
}

}

return 0;
}

好像卡住了?不确定为什么?

最佳答案

您永远不会关闭父级上的 pipe_fd1,因此 grepsort 不知道何时停止读取输入:因为管道读取并且写入端永远不会在父级上关闭,读取器会阻塞等待更多永远不会到达的输入。您需要关闭它。

此外,您不需要 waitpid():管道的工作方式确保输入在整个管道中线性有序地流动。

这是解决了这些问题的工作版本:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

int main(int argc, char *argv[]) {

if (argc != 3) {
printf("Invalid arguments. <dir> <arg>\n");
exit(1);
}

int pipe_fd1[2];
int pipe_fd2[2];
pid_t ls_pid, grep_pid;

pipe(pipe_fd1);

ls_pid = fork();
if (ls_pid == 0) { //first child ls DIR -laR
dup2(pipe_fd1[1], STDOUT_FILENO);
close(pipe_fd1[0]);
execlp("ls", "ls", argv[1], "-laR", NULL);

} else if (ls_pid > 0) {
dup2(pipe_fd1[0], STDIN_FILENO);
close(pipe_fd1[1]);

pipe(pipe_fd2);
grep_pid = fork();

if (grep_pid == 0) { //second child grep ARG
dup2(pipe_fd2[1], STDOUT_FILENO);
close(pipe_fd2[0]);
execlp("grep", "grep", argv[2], NULL);

} else if (grep_pid > 0) { //parent sort
dup2(pipe_fd2[0], STDIN_FILENO);
close(pipe_fd2[1]);
execlp("sort", "sort", NULL);
}

}

return 0;
}

关于c - 程序卡在管道上(exec ls grep sort),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30822887/

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