qfedu-linux-advanced-level/day4/fifo_read.c

35 lines
853 B
C
Raw Normal View History

2023-08-17 19:22:02 +08:00
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <errno.h>
int main()
{
// 创建 fifo 的有名(文件名)管道 if (mkfifo("myfifo", 0755) != 0)
if (mkfifo("myfifo", 0755) != 0)
{
if (errno != EEXIST)
{
perror("mkfifo");
return 1;
}
}
printf("准备以只读方式打开 myfifo\n");
int fd = open("myfifo", O_RDONLY);
printf("open myfifo fd = %d\n", fd);
int n = 1;
while (1)
{
char buf[32] = "";
int len = read(fd, buf, 32); // 阻塞(写进程运行期间),非阻塞(没有写进程运行)
buf[len - 1] = '\0';
printf("第%d次读取的数据(%d Bytes): %s\n", n++, len, buf);
sleep(1);
}
close(fd);
return 0;
}