在上一篇说的管道为匿名管道(pipe),本篇是另一种进程间通信方式,命名管道(fifo)
匿名管道的生命周期随进程
命名管道的生命周期随系统
匿名管道不能在没有血缘关系的进程(如父子,兄弟进程)间进行通信,而命名管道解决了这一问题
它是可以在任何进程间进行通信的一种特殊文件
有两种方式可以进行管道的创建:一是在shell下交互地建立一个命名管道,二是通过函数mkfifo();
一.shell方式下可通过mknod和mkfifo命令来创建管道
二.用mkfifo()创建
#include <sys/types.h>
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
pathname为创建管道的全路径名,mod为创建的命名管道的存取模式和权限(umask会影响其权限)
代码如下:(server为read端,client为write端)
server读端:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main()
{
umask(0);
if(mkfifo("./.fifo",S_IFIFO | 0666)<0){//failed
perror("mkfifo");
return -1;
}
int _fd=open("./.fifo",O_RDONLY);
if(_fd==-1){
perror("open");
return -1;
}
while(1){
char buf[1024];
memset(buf,‘\0‘,sizeof(buf));
ssize_t _size=read(_fd,buf,sizeof(buf));
if(_size<=0){
printf("client has quit or error\n");
break;
}
else if(_size>0){
buf[_size-1]=‘\0‘;
printf("client is say# %s\n",buf);
}
}
close(_fd);
return 0;
}client写端:
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<fcntl.h>
#include<stdlib.h>
#include<unistd.h>
#include<string.h>
int main()
{
int _fd=open("./.fifo",O_WRONLY);
if(_fd==-1){
perror("open");
return -1;
}
while(1){
char buf[1024];
memset(buf,‘\0‘,sizeof(buf));
printf("Please Write Your words:");
fflush(stdout);
if(read(0,buf,sizeof(buf)-1)<0){
perror("read");
return -1;
}
ssize_t _size=write(_fd,buf,strlen(buf));
if(_size<0){
perror("write");
return -1;
}
}
close(_fd);
return 0;
}运行结果如下:
当client端发消息时,server端回立刻收到,当client端退出时,server端会输出“client has quit or error”
原文地址:http://lingdandan.blog.51cto.com/10697032/1762387