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
| /* 程序来源:https://www.bilibili.com/video/av17360025/?p=30
* 程序功能:父子进程间通信,实现`ps aux | grep bash`
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
int main()
{
int fd[2];
if(pipe(fd)){
perror("pipe error");
exit(EXIT_FAILURE);
}
pid_t pid=fork();
if(pid == -1){
perror("fork error");
exit(EXIT_FAILURE);
}
//父进程: `ps aux`
if(pid > 0){
// 写管道的操作,关闭读端
close(fd[0]);
// 文件描述符重定向:STDOUT_FILENO->管道写端
dup2(fd[1], STDOUT_FILENO);
execlp("ps", "ps", "aux", NULL);
perror("execlp");
exit(EXIT_FAILURE);
}
//子进程: `grep --color=auto bash`
else if(pid == 0){
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
execlp("grep", "grep", "--color=auto", "bash", NULL);
perror("execlp");
exit(EXIT_FAILURE);
}
return 0;
}
|
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
55
56
57
58
59
60
61
62
63
64
| /* 程序来源:https://www.bilibili.com/video/av17360025/?p=30
* 程序功能:兄弟进程间通信,实现`ps aux | grep bash`
*/
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <string.h>
#include <wait.h>
int main()
{
int fd[2];
if(pipe(fd)){
perror("pipe error");
exit(EXIT_FAILURE);
}
int i;
pid_t pid[2];
for(i=0; i<2; i++){
pid[i]=fork();
if(pid[i] == -1){
perror("fork error");
exit(EXIT_FAILURE);
}
else if(pid[i] == 0) break;
}
//子进程1: `ps aux`
if(i==0){
// 写管道的操作,关闭读端
close(fd[0]);
// 文件描述符重定向:STDOUT_FILENO->管道写端
dup2(fd[1], STDOUT_FILENO);
execlp("ps", "ps", "aux", NULL);
perror("execlp");
exit(EXIT_FAILURE);
}
//子进程2: `grep --color=auto bash`
else if(i == 1){
close(fd[1]);
dup2(fd[0], STDIN_FILENO);
execlp("grep", "grep", "--color=auto", "bash", NULL);
perror("execlp");
exit(EXIT_FAILURE);
}
else if(i==2){
close(fd[0]);
close(fd[1]);
pid_t wpid;
while((wpid=waitpid(-1, NULL, WNOHANG))!=-1){
if(wpid==0){
continue;
}
printf("waitpid: %lu\n", wpid);
}
}
return 0;
}
|