// 多进程以及ipc管道方式进程间通信 /* 1、父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端。 2、父进程调用fork创建子进程,那么子进程也有两个文件描述符指向同一管道。 3、父进程关闭管道读端,子进程关闭管道写端。父进程可以往管道里写,子进程可以从管道里读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通 */ #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <stdio.h> #include <stdlib.h> #define MAX_LINE 256 // 读数据最大长度 int main(void) { printf("Run at process id: %d!\n\n", getpid()); int fd[2]; // 管道端口,fd[0]读端口,fd[1]写端口 int channel = pipe(fd); // 创建管道 if (channel < 0) { printf("error: make ipc channel fail!\n"); exit(1); } pid_t pid = fork(); // 创建子进程 if (pid < 0) { printf("error: child process fork fail!\n"); exit(1); } if (pid == 0) { // 子进程 char message[] = "Hello father, im your son!\n"; // 待发送数据 printf("Child process %d send to parent: %s\n", getpid(), message); close(fd[0]); // 关闭读端口 write(fd[1], message, sizeof(message) / sizeof(message[0])); // 写数据到写端口 sleep(2); // 模拟发送时间2秒 } else { // 父进程 waitpid(pid, NULL, 0); // 等待子进程信号 close(fd[1]); // 关闭写端口 char message[MAX_LINE]; // 定义接受数据数组 read(fd[0], message, MAX_LINE); // 读端口读取数据 printf("Parent process %d read from %d: %s\n", getpid(), pid, message); } return 0; }
执行结果:
root@DESKTOP-L8AO2MP:/mnt/g/c/test/process# ./a.out
Run at process id: 962!Child process 963 send to parent: Hello father, im your son!
Parent process 962 read from 963: Hello father, im your son!