创建两个进程,在 A 进程中创建一个有名管道,并向其写入数据,通过 B 进程从有名管道中读出数据。
时间: 2024-05-13 14:18:01 浏览: 6
以下是使用 C 语言实现上述功能的代码:
A进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
int main() {
int fd;
char * myfifo = "/tmp/myfifo"; // 定义有名管道文件路径
mkfifo(myfifo, 0666); // 创建有名管道
char buf[50] = "Hello, world!"; // 要写入管道的数据
fd = open(myfifo, O_WRONLY); // 打开管道并写入数据
write(fd, buf, sizeof(buf));
close(fd);
unlink(myfifo); // 删除有名管道
return 0;
}
```
B进程:
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
int main() {
int fd;
char * myfifo = "/tmp/myfifo"; // 定义有名管道文件路径
char buf[50]; // 读取从管道中读取到的数据
fd = open(myfifo, O_RDONLY); // 打开管道并读取数据
read(fd, buf, sizeof(buf));
close(fd);
printf("Received data: %s\n", buf); // 输出从管道中读取到的数据
return 0;
}
```
注意事项:
1. 在创建有名管道时需要使用 `mkfifo` 函数,其第二个参数表示文件权限,这里使用 0666 表示所有用户都有读写权限。
2. 在打开管道时,A进程需要使用 `O_WRONLY` 模式打开,B进程需要使用 `O_RDONLY` 模式打开;读取数据使用 `read` 函数,写入数据使用 `write` 函数。
3. 在使用完有名管道后,需要使用 `unlink` 函数删除该管道。