命名管道
命名管道(NamedPipe)是服务器进程和一个或多个客户进程之间通信的单向或双向管道。不同于匿名管道的是:命名管道可以在不相关的进程之间和不同计算机之间使用。
FIFO,也称为命名管道,它是一种文件类型
#include <sys/stat.h>
int mknod(const char* path, mode_t mod, dev_t dev);
int mkfifo(const char* path, mode_t mod);
调用open()打开命名管道的进程可能会被阻塞。但如果同时用读写方式( O_RDWR)打开,则一定不会导致阻塞;如果以只读方式( O_RDONLY)打开,则调用open()函数的进程将会被阻塞直到有写方打开管道;同样以写方式( O_WRONLY)打开也会阻塞直到有读方式打开管道。
FIFO read端
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
int main()
{
char buf[30]={0};
int nread=0;
if((mkfifo("./file",0600)==-1)&&errno!=EEXIST){
printf("mkfifo failed\n");
perror("why");
}
int fd=open("./file",O_RDONLY);
printf("open success\n");
while(1){
nread=read(fd,buf,30);
printf("read %d byte from fifo,context %s\n",nread,buf);
}
close(fd);
return 0;
}
FIFO write端
#include <stdio.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main()
{
int cnt =0;
char *str="message from fifo";
int fd=open("./file",O_WRONLY);
printf("write success\n");
while(1){
write(fd,str,strlen(str));
sleep(1);
if(cnt==5){
break;
}
cnt++;
}
close(fd);
return 0;
}