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

有名管道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-->

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值