1.FIFO管道
使用fifo管道进行通信的进程间不必有如管道那样的限制关系,将fifo理解为一种普通的文家就行了,只不过该文家具有管道的特性。数据读出时,fifo管道中的数据会被清除。
2.创建FIFO
#include <sys/stat.h>
#include <sys/types.h>
int mkfifo(const char * filename,mode_t mode);
mode指定FIFO的读写权限,filename指定FIFO的文件名称。
//creat_fifo.c
#include <sys/types.h>
#include <sys/stat.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
int main (int argc, char *argv[] )
{
mode_t mode = 0666;
if ( argc != 2 ){
printf("USEMSG: create_fifo {fifoname}/n");
exit (1);
}
if ( ( mkfifo (argv[1], mode )) < 0) {
perror ( "failed to mkfifo" );
exit ( 1 );
}
else
printf ("you successfully create a FIFO name is : %s/n", argv[1]);
exit (0);
}
运行:
alei@alei-desktop:~/linux/code/14$ ./creat_fifo
USEMSG: create_fifo {fifoname}
alei@alei-desktop:~/linux/code/14$ ./creat_fifo fifo1
you successfully create a FIFO name is : fifo1
alei@alei-desktop:~/linux/code/14$
3.FIFO的读写操作
使用open函数打开一个FIFO文件时,open函数的参数flag标志位的O_NONBLOCK标志。
标志 说明
置位 只读open立即返回。当只写open时,如果没有进程为读打开FIFO,则返回-1,并置errno
不置位 只读open要阻塞到有进程为写打开FIFO,只写open要阻塞到有进程为读打开FIFO
如下例子,write_fifo.c打开一个名为fifo1的FIFO文件,分10次写入数据,read_fifo.c先打开fifo1文件,再读取里面的内容。
//write_fifo.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <fcntl.h>
#include <unistd.h>
#include <time.h>
#define BUFSZ PIPE_BUF
int main(void)
{
int fd;
int n,i;
char buf[BUFSZ];
time_t tp;
printf("I am %d/n",getpid());
if((fd=open("fifo1",O_WRONLY))<0){
perror("open");
exit(1);
}
for(i=0;i<10;i++){
time(&tp);
n=sprintf(buf,"write_fifo %d sends %s",getpid(),ctime(&tp));
printf("send msg:%s/n",buf);
if((write(fd,buf,n+1))<0){
perror("write");
close(fd);
exit(1);
}
sleep(3);
}
close(fd);
return 0;
}
//read_fifo.c
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <fcntl.h>
#include <unistd.h>
#define BUFSZ PIPE_BUF
int main(void)
{
int fd;
int len;
char buf[BUFSZ];
mode_t mode = 0666;
if((fd=open("fifo1",O_RDONLY))<0)
{
perror("open");
exit(1);
}
while((len=read(fd,buf, BUFSZ))>0)
printf("read_fifo read: %s",buf);
close(fd);
exit(0);
}