【发布时间】:2011-11-28 18:11:19
【问题描述】:
我知道如何在 Linux 中使用 C 语言创建一个类似于 cat /tmp/txt |grep foo 的管道,但我在实现多个链式管道时遇到问题,例如 cat /tmp/1.txt | uniq -c | sort。如何在 Linux 中使用 pipe() 使用 C 来实现?
更新:我已经想通了。如果有人有同样的问题,这里是代码:
enum PIPES {
READ, WRITE
};
int filedes[2];
int filedes2[2];
pipe(filedes);
pipe(filedes2);
pid_t pid = fork();
if (pid == 0) {
dup2(filedes[WRITE], 1);
char *argv[] = {"cat", "/tmp/1.txt", NULL};
execv("/bin/cat", argv);
exit(0);
}
else {
close(filedes[1]);
}
pid = fork();
if (pid == 0) {
dup2(filedes[READ], 0);
dup2(filedes2[WRITE], 1);
char *argv[] = {"uniq", "-c", NULL};
execv("/usr/bin/uniq", argv);
}
else {
close(filedes2[1]);
}
pid = fork();
if (pid == 0) {
dup2(filedes2[READ], 0);
char *argv1[] = {"sort", NULL};
execv("/usr/bin/sort", argv1);
}
waitpid(pid);
【问题讨论】: