编程实现进程间管道通信。 要求:父子进程共享一无名管道,两个子进程作为发送方分别向管道发送一行信息,父进程先读出子进程P1发来的信息行,将其转换为大写字母输出;再读出子进程P2发来的信息行,将其转换为小写字母输出。
时间: 2024-03-06 07:47:47 浏览: 38
以下是实现该功能的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <ctype.h>
#define BUFFER_SIZE 1024
int main() {
int pipefd[2];
pid_t pid1, pid2;
char buffer[BUFFER_SIZE];
if (pipe(pipefd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
pid1 = fork();
if (pid1 == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid1 == 0) { // 子进程P1
close(pipefd[0]); // 关闭管道读端
char *message = "Hello from P1!";
write(pipefd[1], message, strlen(message)+1);
exit(EXIT_SUCCESS);
} else {
pid2 = fork();
if (pid2 == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid2 == 0) { // 子进程P2
close(pipefd[0]); // 关闭管道读端
char *message = "Hello from P2!";
write(pipefd[1], message, strlen(message)+1);
exit(EXIT_SUCCESS);
} else { // 父进程
close(pipefd[1]); // 关闭管道写端
read(pipefd[0], buffer, BUFFER_SIZE);
printf("Received message from P1: %s\n", buffer);
for (int i = 0; i < strlen(buffer); i++) {
buffer[i] = toupper(buffer[i]);
}
printf("Uppercase message from P1: %s\n", buffer);
read(pipefd[0], buffer, BUFFER_SIZE);
printf("Received message from P2: %s\n", buffer);
for (int i = 0; i < strlen(buffer); i++) {
buffer[i] = tolower(buffer[i]);
}
printf("Lowercase message from P2: %s\n", buffer);
exit(EXIT_SUCCESS);
}
}
return 0;
}
```
该程序首先创建一个无名管道,然后创建两个子进程P1和P2,它们分别向管道写入一行信息。接着父进程从管道读出这两行信息,并分别将其转换为大写和小写字母输出。
其中,`fork()`函数用于创建子进程,`pipe()`函数用于创建管道。`close()`函数用于关闭管道的读或写端,`write()`函数用于向管道写入数据,`read()`函数用于从管道读取数据。`toupper()`和`tolower()`函数分别用于将字符转换为大写和小写字母。
相关推荐
![7z](https://img-home.csdnimg.cn/images/20210720083312.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_c1.png)
![-](https://csdnimg.cn/download_wenku/file_type_column_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)
![](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)