【发布时间】:2014-05-29 22:46:16
【问题描述】:
我必须创建一个使用 fork() 创建两个子进程的管道。 Child 1 将 stdout 重定向到管道的写入端,然后使用 execlp() 执行“ls -al”命令。 Child 2 将其输入从标准输入重定向到管道的读取端,然后执行“sort -n -k 5”命令。创建两个子进程后,父进程等待它们终止,然后才能退出。当我运行我的代码时,它会给出以下输出:
pipes
pipes.c
pipes.c~
父程序与运行命令“ls -al | sort -r -n -k 5”的 shell 执行相同的操作。当我从命令行执行此操作时,我得到以下信息:
-rwxrwxr-x 1 username username 8910 May 28 21:52 pipes
drwxrwxr-x 3 username username 4096 May 28 13:52 ..
drwxrwxr-x 2 username username 4096 May 28 21:52 .
-rwxrwxr-x 1 username username 1186 May 28 21:52 pipes.c
-rwxrwxr-x 1 username username 1186 May 28 19:48 pipes.c~
我的代码中是否有一些我没有正确执行以获取输出的内容?有什么建议吗?
我的代码:
#include <stdio.h>
#include <string.h> // for strlen
#include <stdlib.h> // for exit
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
int main() {
int pipes[2];
pid_t child1, child2;
//PIPE
int p = pipe(pipes);
if (p<0){ //PIPE FAILS
fprintf(stderr, "PIPE FAIL");
exit(2);
}
//CHILD2 PROCESS
child2 = fork(); //CREATING CHILD2
if(child2 < 0){//FORK FAIL
fprintf(stderr, "CHILD2 FORK FAILED\n\n");
exit(3);
}else if(child2 > 0){ //PARENT
//CHILD1 PROCESS
child1 = fork(); //CREATING CHILD1
if(child1 <0){//FORK FAIL
fprintf(stderr, "CHILD1 FORK FAILED\n\n");
exit(4);
}else if(child1 ==0){//CHILD1 P
dup2(pipes[1], 1);
close(pipes[0]);
execlp("ls","-al",NULL);
}
wait(NULL);//PARENT WAITS
}
else if(child2 ==0){ //CHILD2
dup2(pipes[0],0);
close(pipes[1]);
execlp("sort", "-r", "-n", "-k" , "5", NULL);
}
return 0;
}
【问题讨论】: