编制一段程序,实现进程的管道通信。 使用系统调用pipe()建立一条管道线;两个子进程P1和P2分别向管道中写一句话: Child 1 is sending a message! Child 2 is sending a message! 而父进程则从管道中读出来自于两个子进程的信息,显示在屏幕上。 要求父进程先接收子进程P1发来的消息,然后再接收子进程P2发来的消息。
时间: 2024-02-22 17:00:49 浏览: 16
下面是一个简单的实现进程管道通信的程序,使用了系统调用pipe()建立管道,两个子进程向管道中写入信息,父进程从管道中读取信息并显示在屏幕上。
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
#define BUFFER_SIZE 25
#define READ_END 0
#define WRITE_END 1
int main(void)
{
char write_msg1[BUFFER_SIZE] = "Child 1 is sending a message!";
char write_msg2[BUFFER_SIZE] = "Child 2 is sending a message!";
char read_msg[BUFFER_SIZE];
int fd[2];
pid_t pid1, pid2;
if (pipe(fd) == -1) {
fprintf(stderr, "Pipe failed");
return 1;
}
pid1 = fork();
if (pid1 < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid1 == 0) {
// Child process 1
close(fd[READ_END]);
write(fd[WRITE_END], write_msg1, strlen(write_msg1) + 1);
close(fd[WRITE_END]);
exit(0);
} else {
pid2 = fork();
if (pid2 < 0) {
fprintf(stderr, "Fork failed");
return 1;
} else if (pid2 == 0) {
// Child process 2
close(fd[READ_END]);
write(fd[WRITE_END], write_msg2, strlen(write_msg2) + 1);
close(fd[WRITE_END]);
exit(0);
} else {
// Parent process
close(fd[WRITE_END]);
printf("Parent is waiting for child 1...\n");
wait(NULL);
read(fd[READ_END], read_msg, BUFFER_SIZE);
printf("Parent received message from child 1: %s\n", read_msg);
printf("Parent is waiting for child 2...\n");
wait(NULL);
read(fd[READ_END], read_msg, BUFFER_SIZE);
printf("Parent received message from child 2: %s\n", read_msg);
close(fd[READ_END]);
}
}
return 0;
}
```
该程序首先调用pipe()系统调用来建立管道,然后创建两个子进程pid1和pid2,分别向管道中写入信息。父进程等待子进程pid1的结束,然后从管道中读取信息并显示在屏幕上,随后等待子进程pid2的结束,再次从管道中读取信息并显示在屏幕上。最后关闭管道并结束程序。