fifo:命名管道,它是一种特殊文件类型。
特点:
- fifo可以在无关进程之间交换数据,与无名管道不同。
- fifo有路径名,以一种特殊的设备文件形式存在于文件系统中。
命名管道间的数据通信:
当open一个fifo时,是否设置非阻塞标志(O_NONBLOCK)的区别:
- 若没指定O_NONBLOCK,只读open要阻塞到其他进程为写而打开此 fifo。
- 只写open同上,也要阻塞到其他进程为读而打开此 fifo。
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
管道读取:
#include <sys/types.h>
#include <sys/stat.h>
#include <stdio.h>
#include <errno.h>
#include <fcntl.h>int main()
{
int n_read = 0;
char buf[30] = {0};if((mkfifo("./file",0600) == -1) && errno != EEXIST){
printf("mkfifo failuer\n");
perror("why");
}int fd = open("./file",O_RDONLY);
printf("open success\n");while(1){
n_read = read(fd,buf,30);
printf("read %d byte,connect:%s\n",n_read,buf);if(n_read == 0){
break;
}
}
close(fd);
return 0;
}
管道写入:
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <string.h>int main()
{
int cnt = 0;
char *buf = "this is from fifo";int fd = open("./file",O_WRONLY);
printf("write success\n");
while(1){
write(fd,buf,strlen(buf));
sleep(1);
cnt++;if(cnt == 5){
break;
}
}close(fd);
return 0;}