linux fifo 有名管道

来源:互联网 发布:数控机床圆弧编程实例 编辑:程序博客网 时间:2024/04/29 15:44

有名管道可以实现互不关联的进程间的通信


1、创建有名管道

mkfifo

int mkfifo(const char *filename,mode_t mode) 

filename:要创建的管道 

mode:

O_RDONLY:读管道 

O_WRONLY:写管道 

O_RDWR:读写管道 

O_NONBLOCK:非阻塞 

O_CREAT:如果该文件不存在,那么就创建一个新的文件,并用第三的参数为其设置权限 

O_EXCL:如果使用 O_CREAT 时文件存在,那么可返回错误消息。这一参数可测试文件是否存在 

返回值:成功返回0,出错返回-1

测试代码:

#include <sys/types.h> #include <sys/stat.h> #include <errno.h> #include <fcntl.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #define FIFO "/tmp/testfifo"main(int argc,char** argv) {char buf[100]; pid_t pid;memset(buf,0,sizeof(buf)); /*创建有名管道,并设置相应的权限*/       if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST))             printf("cannot create fifoserver\n"); if((pid = fork()) == 0){/*子进程读*/int fd;fd = open(FIFO,O_RDONLY);if(fd < 0){printf("open error\n");exit(-1);}while(1){read(fd, buf, sizeof(buf));printf("read:%s\n",buf);sleep(1);}close(fd);}else if(pid > 0){/*父进程写*/int fd;fd = open(FIFO,O_WRONLY);if(fd < 0){printf("open error\n");exit(-1);}while(1){printf("please input strings\n");fgets(buf, sizeof(buf), stdin);write(fd, buf, strlen(buf));printf("write:%s\n",buf);sleep(1);}close(fd);}else{printf("fork error\n");exit(-1);}unlink(FIFO); return 0;}

输出结果:

please input stringshelloworldread:helloworldwrite:helloworldplease input strings


原创粉丝点击