|
发表于 2024-10-17 17:08:09
|
显示全部楼层
下面是一个使用C语言实现有名管道传输文件内容的简单示例。
### 1. 创建有名管道
确保创建了一个有名管道,你可以使用命令行工具或者在程序中调用`mkfifo`函数。
### 2. 发送进程(Sender)
这个程序读取文件并通过管道发送数据。
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- int main() {
- const char *fifo = "myfifo";
- const char *filename = "input.txt";
-
- int fifo_fd = open(fifo, O_WRONLY); // 打开管道写入
- if (fifo_fd < 0) {
- perror("Open FIFO for writing failed");
- return EXIT_FAILURE;
- }
- FILE *file = fopen(filename, "rb"); // 打开文件读取
- if (!file) {
- perror("Open file for reading failed");
- close(fifo_fd);
- return EXIT_FAILURE;
- }
-
- char buffer[1024];
- size_t bytes;
- while ((bytes = fread(buffer, 1, sizeof(buffer), file)) > 0) {
- write(fifo_fd, buffer, bytes);
- }
- fclose(file);
- close(fifo_fd);
-
- return EXIT_SUCCESS;
- }
复制代码
### 3. 接收进程(Receiver)
这个程序从管道读取数据并保存到另一个文件中。
- #include <stdio.h>
- #include <stdlib.h>
- #include <fcntl.h>
- #include <unistd.h>
- int main() {
- const char *fifo = "myfifo";
- const char *output_filename = "output.txt";
-
- int fifo_fd = open(fifo, O_RDONLY); // 打开管道读取
- if (fifo_fd < 0) {
- perror("Open FIFO for reading failed");
- return EXIT_FAILURE;
- }
- FILE *file = fopen(output_filename, "wb"); // 打开文件写入
- if (!file) {
- perror("Open file for writing failed");
- close(fifo_fd);
- return EXIT_FAILURE;
- }
-
- char buffer[1024];
- ssize_t bytes;
- while ((bytes = read(fifo_fd, buffer, sizeof(buffer))) > 0) {
- fwrite(buffer, 1, bytes, file);
- }
- fclose(file);
- close(fifo_fd);
-
- return EXIT_SUCCESS;
- }
复制代码
### 4. 编译和运行
使用以下命令编译两个程序:
- gcc sender.c -o sender
- gcc receiver.c -o receiver
复制代码
然后分别在两个终端中运行:
1. 运行接收进程:
2. 运行发送进程:
通过上述步骤,你就可以使用C语言实现有名管道在两个进程间传输文件内容。确保网络环境支持有名管道,文件路径要正确配置。
以上回复来自 FishC AI 小助理,如未能正确解答您的问题,请继续追问。 |
|