多进程的通信方式
1. 管道(Pipes)
管道是一种最简单的进程间通信方式,分为匿名管道和命名管道两种类型。匿名管道通常用于具有亲缘关系的进程间通信,而命名管道则用于无亲缘关系的进程间通信。
使用情景
- 父子进程通信。
- 同一进程中不同线程通信。
代码示例
本代码使用的是匿名管道。调用fork()之后,父进程和子进程会在同一位置继续执行代码,从fork()之后的那一行开始。但是它们各自拥有独立的内存空间和执行环境。
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#define MSG_SIZE 64
int main() {
int pipefd[2];
char msg[MSG_SIZE];
pid_t pid;
// 创建管道
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
}
if (pid == 0) { // 子进程
close(pipefd[1]); // 关闭写入端
// 从管道中读取消息
if (read(pipefd[0], msg, MSG_SIZE) == -1) {
perror("read");
exit(EXIT_FAILURE);
}
printf("Child received message: %s\n", msg);
close(pipefd[0]); // 关闭读取端
} else { // 父进程
close(pipefd[0]); // 关闭读取端
// 向管道中写入消息
if (write(pipefd[1], "Hello from parent!", 18) == -1) {
perror("write");
exit(EXIT_FAILURE);
}
close(pipefd[1]); // 关闭写入端
}
return 0;
}
运行结果:
Child received message: Hello from parent!