我的老师给了我们一个练习作业,让我们在操作系统课上学习。任务是将三个进程连接在一起并同时执行标题中的命令。我们只允许在实现时使用这些命令:
dup2()
one of the exec()
fork()
pipe()
close()
我可以把两个管在一起,但我不知道怎么做三个。有人可以告诉我怎么做,或者至少给我指出正确的方向吗?
到目前为止,这是我的代码:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int pfd[2];
int pfdb[2];
int pid;
if (pipe(pfd) == -1) {
perror("pipe failed");
exit(-1);
}
if ((pid = fork()) < 0) {
perror("fork failed");
exit(-2);
}
if (pid == 0) {
close(pfd[1]);
dup2(pfd[0], 0);
close(pfd[0]);
execlp("ps", "ps", "-ef", (char *) 0);
perror("ps failed");
exit(-3);
}
else {
close(pfd[0]);
dup2(pfd[1], 1);
close(pfd[1]);
execlp("grep", "grep", "darrowr", (char *) 0);
perror("grep failed");
exit(-4);
}
exit(0);
}
任何帮助,将不胜感激。哎呀,如何完成它的教程将是奇妙的!