1 创建fifo :
/**
* https://man7.org/linux/man-pages/man3/mkfifo.3.html
*/
int main() {
if (mkfifo("fifo123", 0666) != 0) {
perror("mkfifo");
exit(EXIT_FAILURE);
}
printf("success");
return EXIT_SUCCESS;
}
执行成功之后,可以在当前目录通过ls 查看确认是否有 fifo123 这个文件.
2 写入fifo
/**
* https://man7.org/linux/man-pages/man3/mkfifo.3.html
*/
int main() {
char a[] = "i am the sender";
int fd = open("fifo123", O_WRONLY);
write(fd, a, strlen(a));
close(fd);
return EXIT_SUCCESS;
}
3 读取
/**
* https://man7.org/linux/man-pages/man3/mkfifo.3.html
*/
int main() {
int fd = open("fifo123", O_RDONLY);
printf("%d\n", fd);
char buf[1024];
int len = read(fd, buf, 1024);
buf[len] = '\0';
printf("%s", buf);
close(fd);
return EXIT_SUCCESS;
}
注意2 和3 要同时执行,不然会一直阻塞在open 函数.