用fifo写0-9再读0-9
时间: 2024-05-10 22:18:11 浏览: 18
这里提供一种简单的C语言代码实现方法:
```c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#define FIFO_NAME "/tmp/my_fifo"
int main()
{
int fd;
char buffer[10];
// 创建FIFO
if (mkfifo(FIFO_NAME, S_IRUSR | S_IWUSR) == -1)
{
perror("mkfifo error");
exit(EXIT_FAILURE);
}
// 写入0-9
printf("Writing data to the FIFO...\n");
fd = open(FIFO_NAME, O_WRONLY);
for (int i = 0; i < 10; i++)
{
sprintf(buffer, "%d", i);
write(fd, buffer, sizeof(buffer));
printf("%s ", buffer);
}
printf("\n");
close(fd);
// 读取0-9
printf("Reading data from the FIFO...\n");
fd = open(FIFO_NAME, O_RDONLY);
while (read(fd, buffer, sizeof(buffer)) > 0)
{
printf("%s ", buffer);
}
printf("\n");
close(fd);
// 删除FIFO
unlink(FIFO_NAME);
return 0;
}
```
这段代码先创建了一个FIFO文件,然后向FIFO中写入0-9,最后从FIFO中读取数据并打印输出。请注意,在写入数据时,我们使用了sprintf函数将整数转换为字符串,再使用write函数将字符串写入FIFO;在读取数据时,我们使用了while循环,每次调用read函数读取FIFO中的数据。最后,我们使用unlink函数删除FIFO文件。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.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)