// 多進程以及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!