085. 使用C语言实现简单的进程间通信
085. 使用C语言实现简单的进程间通信
在C语言中,进程间通信(IPC)是多个进程之间交换数据的一种方式。Linux系统提供了多种IPC机制,包括管道(Pipes)、消息队列(Message Queues)、共享内存(Shared Memory)和信号(Signals)。以下将分别实现这些简单的IPC机制。
1. 管道(Pipes)
管道是一种简单的IPC机制,用于在父子进程之间单向通信。匿名管道只能用于具有亲缘关系的进程之间,而命名管道(FIFO)可以用于不相关的进程之间。
示例代码:匿名管道
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
int pipefds[2];
pid_t pid;
// 创建管道
if (pipe(pipefds) == -1) {
perror("pipe");
exit(1);
}
pid = fork();
if (pid == -1) {
perror("fork");
exit(1);
}
if (pid == 0) {
// 子进程
close(pipefds[1]); // 关闭写端
char buffer[80];
read(pipefds[0], buffer, sizeof(buffer)); // 从管道读取数据
printf("子进程收到的消息:%s\n", buffer);
close(pipefds[0]); // 关闭读端
} else {
// 父进程
close(pipefds[0]); // 关闭读端
char message[] = "Hello, World!";
write(pipefds[1], message, sizeof(message)); // 向管道写入数据
close(pipefds[1]); // 关闭写端
wait(NULL); // 等待子进程结束
}
return 0