Linux 进程间通讯之有名管道方式

来源:互联网 发布:经济互助委员会 知乎 编辑:程序博客网 时间:2024/05/01 06:32

有名管道mkfifo

int   mkfifo(const char *pathname, mode_t mode)

pathname: FIFO文件名

mode: 属性

一旦创建了了FIFO,就可open去打开它,可以使用openreadclose等去操作FIFO

当打开FIFO时,非阻塞标志(O_NONBLOCK)将会对读写产生如下影响:

1、没有使用O_NONBLOCK:访问要求无法满足时进程将阻塞。如试图读取空的FIFO,将导致进程阻塞;

2、使用O_NONBLOCK:访问要求无法满足时不阻塞,立即出错返回,errnoENXIO

示例:

读管道example

#include <stdio.h>

#include <sys/stat.h>

#include <fcntl.h>

#include <unistd.h>

#include <string.h>

#include <stdlib.h>

#define P_FIFO         "/tmp/p_fifo"

int main(int argc, char** argv){

         charcache[100];

         intfd;

         memset(cache,0, sizeof(cache));                               //初始化内存

         if(access(P_FIFO,F_OK)==0){                                        //管道文件存在

                   execlp("rm","-f", P_FIFO, NULL);                      //删掉

                   printf("access.\n");

         }

         if(mkfifo(P_FIFO, 0777) < 0){            

                   printf("createnamed pipe failed.\n");

         }

         fd= open(P_FIFO,O_RDONLY|O_NONBLOCK);        //     非阻塞方式打开,只读

         while(1){                                                                             //     一直去读

                   memset(cache,0, sizeof(cache));

                   if((read(fd,cache, 100)) == 0 ){                           //     没有读到数据

                            printf("nodata:\n");

                   }

                   else

                            printf("getdata:%s\n", cache);                //     读到数据,将其打印

                            sleep(1); //休眠1s

         }

         close(fd);

         return0;

}

写管道example

#include <stdio.h>

#include <fcntl.h>

#include <unistd.h>

#define P_FIFO "/tmp/p_fifo"

int main(int argc, char argv[]){

         intfd;

         if(argc< 2){

                   printf("pleaseinput the write data.\n");

         }

         fd= open(P_FIFO,O_WRONLY|O_NONBLOCK);                //非阻塞方式

         write(fd,argv[1], 100);                                                            //argv[1]写道fd里面去

         close(fd);

}

测试:

root--> ./mkfifo_r
no data:
no data:
get data:linuxdba
no data:
no data:
no data:
no data:
no data:

......

root--> ./mkfifo_w linuxdba
root-->

0 0
原创粉丝点击