进程间通信(IPC)2 ------ 有名管道

来源:互联网 发布:刀剑神域第二季 知乎 编辑:程序博客网 时间:2024/05/21 18:44

      管道的一个不足之处是没有名字,因此只能在具有亲缘关系的进程之间通信。而“有名管道”与此不同,它提供了一个路径名与之关联,作为一个设备文件存在,即使无亲缘关系的进程之间,只要能访问该路径,也可以通过FIFO进行通信。FIFO总是按照先进先出的原则工作,第一个被写入的数据将首先从管道中读出。

      函数原型:

#include <sys/types.h>#include <sys/stat.h>int mkfifo(const char *path,mode_t mode);

      path为创建有名管道的路径名;mode为创建有名管道的模式,指明其存取权限。函数调用成功返回0,失败返回-1。

      使用一个存在的有名管道之前,需要用open()将其打开。因为有名管道是一个存在于硬盘上的文件,而管道是存在于内存中的特殊文件。

      以下程序演示有名管道在无亲缘关系的进程之间如何通信。

//procwriter.c#include <stdio.h>#include <stdlib.h>#include <string.h>#include <fcntl.h>#include <sys/types.h>#include <sys/stat.h>#define FIFO_NAME"myfifo"#define BUF_SIZE1024int main(void){int     fd;charbuf[BUF_SIZE] = "Hello procwrite, I come from process named procread!";umask(0);//指明创建一个有名管道且存取权限为0666,即创建者、与创建者同组的用户、其他用户对该有名管道的访问权限都是可读可写if (mkfifo (FIFO_NAME, S_IFIFO | 0666) == -1){perror ("mkfifo error!");exit (1);}if((fd = open (FIFO_NAME, O_WRONLY) ) == -1)/*以写方式打开FIFO*/{perror ("fopen error!");exit (1);}write (fd, buf, strlen(buf)+1); /*向FIFO写数据*/close (fd);exit (0);}

procreader.c

#include <stdio.h>#include <stdlib.h>#include <unistd.h>#include <sys/stat.h>#include <fcntl.h>#include <sys/types.h>#define FIFO_NAME  "myfifo"#define BUF_SIZE    1024int main(void){        int     fd;        char    buf[BUF_SIZE];        umask (0);        fd = open(FIFO_NAME, O_RDONLY);        read (fd, buf, BUF_SIZE);        printf ("Read content: %s\n", buf);        close (fd);        exit (0);}

      首先运行procwrite(运行后处于阻塞状态),打开另一个终端运行程序procread。结果如下:



原创粉丝点击