编写c代码,进程A创建一个子进程B, B发送消息“12345678”,A分两次接收,一次接收4个字符。
时间: 2024-03-15 22:44:56 浏览: 38
以下是对应的 C 代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/wait.h>
int main() {
int fd[2]; // 管道文件描述符
pid_t pid; // 子进程ID
char msg[] = "12345678"; // 要发送的消息
char buf[5]; // 每次接收 4 个字符的缓冲区
int status; // 子进程结束状态
// 创建管道
if (pipe(fd) == -1) {
perror("pipe");
exit(EXIT_FAILURE);
}
// 创建子进程
pid = fork();
if (pid == -1) {
perror("fork");
exit(EXIT_FAILURE);
} else if (pid == 0) {
// 子进程 B
close(fd[0]); // 关闭管道读端
write(fd[1], msg, strlen(msg)); // 向管道写入消息
close(fd[1]); // 关闭管道写端
exit(EXIT_SUCCESS);
} else {
// 父进程 A
close(fd[1]); // 关闭管道写端
for (int i = 0; i < 2; i++) {
int n = read(fd[0], buf, 4); // 从管道读取 4 个字符
buf[n] = '\0'; // 在读取结果后添加字符串结尾符
printf("Received: %s\n", buf);
}
close(fd[0]); // 关闭管道读端
waitpid(pid, &status, 0); // 等待子进程结束
}
return 0;
}
```
注释已经说明了每个步骤的作用。在这个程序中,首先创建一个管道,然后创建一个子进程 B,在子进程 B 中向管道写入消息。接着,父进程 A 从管道中读取两次,每次读取 4 个字符,即总共读取 8 个字符,最后等待子进程 B 结束。在父进程 A 中,每次读取后输出接收到的字符串。需要注意的是,每次读取后需要手动添加字符串结尾符,否则输出可能会出现乱码。
相关推荐
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![doc](https://img-home.csdnimg.cn/images/20210720083327.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)