由父进程创建一个管道,然后再创建3个子进程,并由这三个子进程用管道与父进程之间进行通信:子进程发送信息,父进程等三个子进程全部发完消息后再接收信息。通信的具体内容可根据自己的需要随意设计,要求能够实验阻塞型读写过程的各种情况,并要求实现进程间对管道的互斥访问。运行程序,观察各种情况下,进程实际读写的字节数以及进程阻塞唤醒情况。
时间: 2024-02-20 12:02:23 浏览: 26
好的,这是一个比较复杂的问题,需要一定的代码实现。以下是一个可能的实现,供参考:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/wait.h>
#define BUFFER_SIZE 256
int main(int argc, char *argv[]) {
int fd[2], n;
pid_t pid[3];
char buffer[BUFFER_SIZE];
fd_set rfds, wfds;
int retval;
// 创建管道
if (pipe(fd) == -1) {
perror("pipe failed");
exit(EXIT_FAILURE);
}
// 创建三个子进程
for (int i = 0; i < 3; i++) {
pid[i] = fork();
if (pid[i] == -1) {
perror("fork failed");
exit(EXIT_FAILURE);
} else if (pid[i] == 0) {
// 子进程
close(fd[0]); // 关闭管道读端
// 发送消息
sprintf(buffer, "Message from child process %d\n", i);
n = strlen(buffer);
if (write(fd[1], buffer, n) != n) {
perror("write failed");
exit(EXIT_FAILURE);
}
exit(EXIT_SUCCESS);
}
}
// 父进程
close(fd[1]); // 关闭管道写端
// 等待子进程发送消息
for (int i = 0; i < 3; i++) {
waitpid(pid[i], NULL, 0);
}
// 接收消息
int total = 0;
while (total < 3 * BUFFER_SIZE) {
FD_ZERO(&rfds);
FD_SET(fd[0], &rfds);
// 阻塞等待管道可读
retval = select(fd[0] + 1, &rfds, NULL, NULL, NULL);
if (retval == -1) {
perror("select failed");
exit(EXIT_FAILURE);
}
if (FD_ISSET(fd[0], &rfds)) {
n = read(fd[0], buffer, BUFFER_SIZE);
if (n == -1) {
perror("read failed");
exit(EXIT_FAILURE);
} else if (n == 0) {
printf("EOF\n");
break;
} else {
total += n;
buffer[n] = '\0';
printf("Received message: %s", buffer);
}
}
}
close(fd[0]);
exit(EXIT_SUCCESS);
}
```
这个程序实现了以下功能:
1. 父进程创建了一个管道,然后创建了三个子进程。
2. 每个子进程向管道中写入一条消息。
3. 父进程等待三个子进程全部发送完消息后开始从管道中读取消息。
4. 父进程使用 `select` 函数阻塞等待管道可读,并在管道可读时读取数据。
5. 每个子进程和父进程都使用了管道的互斥访问,因为写入和读取操作都是原子操作,不会相互干扰。
你可以根据需要修改代码,添加更多的功能或者测试不同的读写情况。
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![docx](https://img-home.csdnimg.cn/images/20210720083331.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)