父子进程执行ps_aux_grep_bash思路分析和实现

输入grep bash 回车之后默认情况下是等待终端输入数据
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
| #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <unistd.h> #include <sys/wait.h>
int main() { int fd[2]; int ret = pipe(fd); if(ret<0) { perror("pipe error"); return -1; }
pid_t pid = fork(); if(pid<0) { perror("fork error"); return -1; } else if(pid>0) { close(fd[0]);
dup2(fd[1], STDOUT_FILENO); execlp("ps", "ps", "aux", NULL);
perror("execlp error"); } else { close(fd[1]); dup2(fd[0], STDIN_FILENO);
execlp("grep", "grep", "--color=auto", "bash", NULL);
perror("execlp error"); }
return 0; }
|