编制一段程序,实现进程管道通信。使用系统调用pipe()建立一条无名管道。两个子进程P1和P2分别向管道各写一句话: Child process 1 is sending message! Child process 2 is sending message!
时间: 2025-01-29 21:13:33 浏览: 52
在Unix/Linux环境中,可以使用C语言编写一个简单的程序来演示进程管道通信。首先,我们需要包含必要的头文件并定义main函数。这里是一个简化的示例:
```c
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
#define BUFFER_SIZE 1024
int main(int argc, char *argv[]) {
// 创建管道
int pipe_fds[2];
if (pipe(pipe_fds) < 0) {
perror("Failed to create pipe");
exit(EXIT_FAILURE);
}
// 父进程操作
pid_t p1 = fork();
if (p1 == 0) { // 子进程 P1
close(pipe_fds[1]); // 关闭接收端
write(pipe_fds[0], "Child process 1 is sending message!\n", strlen("Child process 1 is sending message!\n"));
printf("Message from P1 sent.\n");
_exit(EXIT_SUCCESS); // 子进程结束
} else if (p1 > 0) { // 父进程
close(pipe_fds[0]); // 关闭发送端
pid_t p2 = fork(); // 创建子进程 P2
if (p2 == 0) { // 子进程 P2
close(pipe_fds[1]);
read(pipe_fds[0], BUFFER_SIZE, &BUFFER_SIZE); // 接收消息
printf("Received message from P1: %s\n", BUFFER_SIZE ? pipe_fds[0] : "(empty)");
_exit(EXIT_SUCCESS);
}
wait(NULL); // 等待P1完成
read(pipe_fds[0], BUFFER_SIZE, &BUFFER_SIZE); // 接收P1的消息
printf("Received message from P1: %s\n", BUFFER_SIZE ? pipe_fds[0] : "(empty)");
close(pipe_fds[1]); // 关闭接收端
write(pipe_fds[0], "Child process 2 is sending message!\n", strlen("Child process 2 is sending message!\n"));
printf("Message from P2 sent.\n");
// 等待P2完成
wait(NULL);
printf("Child process 2 finished.\n");
} else {
perror("Fork failed");
exit(EXIT_FAILURE);
}
return 0;
}
```
当你运行这个程序,它会创建两个子进程(P1 和 P2),每个子进程都会向管道的一端发送一条消息,然后等待对方接收到消息。父进程会显示收到的信息。
阅读全文
相关推荐

















