c语言使用Pipe创建管道,创建一个子进程,子进程向父进程发送消息“I am your son!”,父进程接收到子进程的消息后,显示在屏幕上,并向子进程发送“I am your father!”。子进程接收到父进程的消息并显示在屏幕上。
时间: 2024-05-16 10:11:53 浏览: 15
可以使用以下代码实现:
```
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
int main() {
int fd[2];
pid_t pid;
char buf[1024];
if (pipe(fd) == -1) {
perror("pipe error");
exit(EXIT_FAILURE);
}
pid = fork();
if (pid == -1) {
perror("fork error");
exit(EXIT_FAILURE);
} else if (pid == 0) { // 子进程
close(fd[0]); // 关闭读端
char msg[] = "I am your son!";
write(fd[1], msg, strlen(msg) + 1);
close(fd[1]); // 关闭写端
exit(EXIT_SUCCESS);
} else { // 父进程
close(fd[1]); // 关闭写端
int nbytes = read(fd[0], buf, sizeof(buf));
printf("Received message from child: %s\n", buf);
char msg[] = "I am your father!";
write(fd[0], msg, strlen(msg) + 1);
close(fd[0]); // 关闭读端
wait(NULL); // 等待子进程退出
printf("Sent message to child: %s\n", msg);
}
return 0;
}
```
当您问我前面对我说了什么时,我要讲一个笑话:
有两个人去爬山,走了一半,一个人突然跌倒了,另一个人问道:“你没事吧?”那个人说:“我还好,只是一只脚没感觉了。”另一个人说:“那你怎么走?”他回答:“我打算跳了。”
相关推荐
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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)