Skip to content
This repository was archived by the owner on Jun 17, 2025. It is now read-only.

Commit 5ff6237

Browse files
committed
feat: 父子进程间,兄弟子进程间,使用管道 pipe 通信
1 parent 4ed67bd commit 5ff6237

4 files changed

Lines changed: 58 additions & 5 deletions

File tree

11_pipe/childProcessPipe

8.54 KB
Binary file not shown.

11_pipe/childProcessPipe.cpp

Lines changed: 57 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,57 @@
1+
#include <stdio.h>
2+
#include <unistd.h>
3+
#include <sys/wait.h>
4+
5+
int main(int argc, char *argv[])
6+
{
7+
int fd[2]; //用来标记管道的两端的文件描述符
8+
int ret = pipe(fd); //创建管道 pipe. fd[2] 是固定的输出参数
9+
10+
if (ret == -1) {
11+
perror("[pipe create file] ");
12+
return 0;
13+
}
14+
15+
int pipeRead = fd[0];
16+
int pipeWrite = fd[1];
17+
18+
int i = 0;
19+
for ( ; i < 2; i++) {
20+
pid_t pid = fork();
21+
22+
if (pid == 0)
23+
break;
24+
25+
if (pid == -1)
26+
perror("[creator process file:]");
27+
28+
}
29+
30+
if (i == 0) { //child process 1
31+
dup2(pipeWrite, STDOUT_FILENO);
32+
close(pipeRead);
33+
execlp("ps", "ps", "aux", NULL);
34+
} else if (i == 1) { //child process 2
35+
dup2(pipeRead, STDIN_FILENO);
36+
close(pipeWrite);
37+
execlp("grep", "grep", "bash", "--color=auto", NULL);
38+
} else if (i == 2) { //parent process
39+
close(pipeWrite);
40+
close(pipeRead);
41+
42+
// sleep(2);
43+
int wpid;
44+
while ( wpid = waitpid(-1, NULL, WNOHANG) != -1) { //回收子进程
45+
if (wpid == 1) ///sbin/init splash 进程 /sbin/launchd
46+
continue;
47+
48+
if (wpid == 0)
49+
continue;
50+
51+
printf("child dide pid = %d\n", wpid);
52+
}
53+
}
54+
55+
printf("pipeWrite = %d, pipeRead = %d\n", pipeWrite, pipeRead);
56+
return 0;
57+
}

11_pipe/myPipe

-48 Bytes
Binary file not shown.

11_pipe/myPipe.cpp

Lines changed: 1 addition & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -26,10 +26,6 @@ int main(int argc, char *argv[])
2626
close(pipeWrite);
2727
execlp("grep", "grep", "bash", "--color=auto", NULL);
2828
}
29-
30-
close(pipeWrite);
31-
close(pipeRead);
32-
33-
printf("pipeWrite = %d, pipeRead = %d\n", pipeWrite, pipeRead);
29+
3430
return 0;
3531
}

0 commit comments

Comments
 (0)