编写一个C程序,演示如何使用FIFO文件系统实现两个独立进程之间的通信,并让其中一个进程向FIFO中写入数据,另一个进程从FIFO中读取数据。
时间: 2024-10-01 08:05:56 浏览: 23
Linux下进程间通信FIFO演示程序
5星 · 资源好评率100%
在Linux系统中,FIFO(即命名管道)是一种特殊类型的文件,可以在文件系统上直接创建,用于进程间通信。下面是一个简单的C程序示例,展示如何使用FIFO实现进程间的双向通信:
**writer.c**
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#define FIFO_NAME "/tmp/myfifo"
void write_to_fifo(int fd) {
char message[] = "This is a message from the writer process.";
write(fd, message, strlen(message));
}
int main() {
int fifo_fd;
if (mkfifo(FIFO_NAME, 0666) != 0) {
perror("Failed to create FIFO");
exit(EXIT_FAILURE);
}
fifo_fd = open(FIFO_NAME, O_WRONLY); // Open the FIFO for writing
if (fifo_fd < 0) {
perror("Failed to open FIFO for writing");
exit(EXIT_FAILURE);
}
write_to_fifo(fifo_fd);
printf("Wrote to FIFO successfully.\n");
close(fifo_fd);
remove(FIFO_NAME); // Remove the FIFO after use
return 0;
}
```
**reader.c**
```c
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
int main() {
int fifo_fd;
char buffer[100];
fifo_fd = open(FIFO_NAME, O_RDONLY); // Open the FIFO for reading
if (fifo_fd < 0) {
perror("Failed to open FIFO for reading");
exit(EXIT_FAILURE);
}
ssize_t bytes_read = read(fifo_fd, buffer, sizeof(buffer));
if (bytes_read <= 0) {
perror("Failed to read from FIFO");
exit(EXIT_FAILURE);
}
buffer[bytes_read] = '\0'; // Add null terminator
printf("Read from FIFO: %s\n", buffer);
close(fifo_fd);
remove(FIFO_NAME); // Remove the FIFO after use
return 0;
}
```
**步骤说明:**
1. `writer.c` 创建FIFO(如果不存在),打开它并写入消息,然后删除FIFO。
2. `reader.c` 打开FIFO并读取消息,然后删除FIFO。
要在Linux终端上运行这个程序,先运行`writer.c`创建FIFO,然后在新的终端窗口运行`reader.c`读取消息。
阅读全文