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

命名管道(FIFO)

2016-04-17 16:29 363 查看
一、命名管道:两个不相关的进程通过一个路径名关联,即,只要可以访问该路径,就能实现进程间的通信(先入先出)。
二、创建函数原型:int mkfifo(const char*path, mode_t mode); //成功返回0,失败返回-1
三、代码实现:
//write端
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#define _PATH_ "/tmp/fifo.tmp"
#define _SIZE_ 1024
int main()
{
umask(0);
int ret = mkfifo(_PATH_, S_IFIFO|0666);
if(ret == -1)
{
perror("mkfifo");
return 1;
}
int fd = open(_PATH_, O_RDWR);
if(fd < 0)
{
perror("open");
}
char buf[_SIZE_];
memset(buf, '\0', sizeof(buf));
while(1)
{
scanf("%s", buf);
int ret = write(fd, buf, strlen(buf)+1);
if(ret < 0)
{
perror("write");
break;
}
if(strncmp(buf, "quit", 4) == 0)
{
break;
}
}
close(fd);
return 0;
}
//read端
#include<stdio.h>
#include<sys/types.h>
#include<sys/stat.h>
#include<unistd.h>
#include<string.h>
#include<fcntl.h>
#include<stdlib.h>
#define _PATH_ "/tmp/fifo.tmp"
#define _SIZE_ 1024

int main()
{
int fd = open(_PATH_, O_RDWR);
if(fd < 0)
{
perror("open");
return 1;
}
char buf[_SIZE_];
memset(buf, '\0', sizeof(buf));
while(1)
{
int ret = read(fd, buf, sizeof(buf));
if(ret <= 0)
{
perror("read");
break;
}
printf("%s\n", buf);
if(strncmp(buf, "quit", 4) == 0)
{
break;
}
}
close(fd);
return 0;
}
四、实现通信:





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