两进程进行匿名管道传输信息
时间: 2023-09-15 17:16:07 浏览: 47
在 Linux 系统下,可以使用 `pipe` 系统调用来创建匿名管道。匿名管道是一种半双工的通信机制,只能用于父子进程或兄弟进程之间的通信。
下面是一个使用匿名管道进行进程间通信的例子:
```c
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1024
int main()
{
int fd[2];
pid_t pid;
char buffer[BUFFER_SIZE];
// 创建匿名管道
if (pipe(fd) < 0) {
printf("Create pipe error!\n");
return -1;
}
pid = fork();
if (pid < 0) {
printf("Fork error!\n");
return -1;
} else if (pid > 0) { // 父进程写入数据
close(fd[0]); // 关闭读端
while (1) {
printf("Enter message to send: ");
fgets(buffer, BUFFER_SIZE, stdin);
if (strcmp(buffer, "exit\n") == 0) {
break;
}
write(fd[1], buffer, strlen(buffer));
}
close(fd[1]); // 关闭写端
} else { // 子进程读取数据
close(fd[1]); // 关闭写端
while (1) {
ssize_t count = read(fd[0], buffer, BUFFER_SIZE);
if (count == 0) {
break;
}
buffer[count] = '\0';
printf("Received message: %s", buffer);
}
close(fd[0]); // 关闭读端
}
return 0;
}
```
上面的代码中,父进程和子进程通过管道进行通信。父进程从标准输入读取数据,然后通过管道写入到子进程;子进程从管道读取数据,然后打印输出。当父进程输入 `exit` 时,程序退出。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.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_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)