您的位置:首页 > 运维架构 > Linux

Linux 进程通信之 命名管道

2017-03-31 22:09 447 查看

命名管道

(一)概念

匿名管道只能用于具有亲缘关系的进程间通信,而命名管道(FIFO)解决了这个问题!FIFO不同于管道之处在于
它提供一个路径名与之关联,以FIFO的文件形式存储在文件系统中。命名管道是一个设备文件,因此,即使继承创建FIFO的进程不存在亲缘关系,只要可以访问该路径,就能通过FIFO相互通信。

(二)系统调用函数介绍

命名管道创建
int mkfifo (comst char* path, mode_t mode)
参数介绍:
①: path  为创建命名管道的全路径名,比如 " . log " 当前路径下的一个log文件即 通信的公共资源
②: mode 为创建的命名管道的模式,指明其存取权限 ,例 S_IFIFO | 0666 (创建一个命名管道且存取权限位0666,即创建者 与创建者同组的用户 其他用户对该命名管道的访问权限都是可读可写,这里注意umask 对生成管道文件权限的影响)

返回值:
创建成功返回 0, 否则返回 -1

利用系统调用open 、write、read来进行对管道的读写操作,这里不一一介绍

(三)代码演示

client.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
int main()
{
int fb = open("./log", O_WRONLY);
if(fb < 0){
perror("open");
return 2;
}

char buf[128];
while(1){
printf("please enter:");
fflush(stdout);
ssize_t _a = read(0, buf, sizeof(buf)-1);
if(_a > 0 ){
buf[_a-1] = '\0';
ssize_t _s = write(fb, buf, strlen(buf));
}else{
perror("write");
return 3;
}

}
close(fb);
return 0;
}


server.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int main()
{
if(mkfifo("./log", 0666|S_IFIFO) < 0){
perror("mkfifo");
return 1;
}

int fb = open("./log", O_RDONLY);
if(fb < 0){
perror("open");
return 2;
}

char buf[128];
while(1){
ssize_t _s = read(fb, buf, sizeof(buf)-1);
if(_s > 0 ){
buf[_s] = '\0';
printf("%s\n",buf);
}else if(_s == 0){
printf("client is qute, i am quiting\n");
break;
}else{
perror("read");
return 3;
}

}
close(fb);
return 0;
}


结果演示:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: