命名管道(有名管道)的使用-例程序

转自 https://blog.csdn.net/cxyzyywoaini/article/details/87464220

命名管道的读取端  Fifo_read.c

#include<sys/types.h>

#include<sys/stat.h>

#include<errno.h>

#include<fcntl.h>

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#define FIFO "/tmp/myfifo" //命名管道设备名称


int main(int argc,char** argv)

{

int fd;

char r_buf[100];

int nread;


if((mkfifo(FIFO,O_CREAT|O_EXCL|O_RDWR)<0) && (errno!=EEXIST)) //建立命名管道,判断管道是否建立成功

printf("cannot creat fifo \n");

printf("prepareing for reading bytes . .\n");


fd=open(FIFO,O_RDONLY,0); //打开命名管道

if(fd<0){

printf("fifo open error\n");

exit(1);

}

while(1){

memset(r_buf,0,sizeof(r_buf));

if((nread=read(fd,r_buf,10))==-1){ //将命名管道里的内容读取到r_buf[]中

if(errno==EAGAIN)

printf("no data yet\n");

}


printf("read len=%d str=%s from FIFO,nread=%d\n",strlen(r_buf),r_buf,nread);

sleep(1);

}


close(fd);

return 0;

}
  1.  

  2. 命名管道写入端 Fifo_write.c

 

#include<sys/types.h>

#include<sys/stat.h>

#include<errno.h>

#include<fcntl.h>

#include<stdio.h>

#include<string.h>

#include<stdlib.h>

#define FIFO "/tmp/myfifo" //命名管道设备名称


int main(int argc,char** argv)

{

int fd;

char w_buf[100];

char ww_buf[1024];

int nwrite;


if(argc==1){

printf("arg error\n");

exit(0);

}

if((mkfifo(FIFO,O_CREAT|O_EXCL)<0)&&(errno!=EEXIST)) //打开或创建命名管道

printf("cannot creat fifo \n");

printf("prepareing for writing bytes . .\n");


fd=open(FIFO,O_WRONLY,0); //打开命名管道这个文件

if(fd<0){

if(errno==ENXIO)

printf("open error; no reading process\n");

printf("fifo open error\n");

exit(1);

}


/*

for(i=0;i<(argv-1);i++){

printf("%d++",i);

strcpy(w_buf,argv[i+1]);

printf("%d++",i);

strcpy(ww_buf,w_buf);

}

*/

strcpy(w_buf,argv[1]); //将命令行的第一个参数出个数组,将数组的内容写入到命名管道中

while(1){

if((nwrite=write(fd,w_buf,strlen(w_buf)))==-1){

if(errno==EAGAIN)

printf("the FIFO has not been read yet.\n");

}else

printf("write %s to the FIFO\n",w_buf);

sleep(1);

}

close(fd);


return 0;

}
  1.  

在命令行输入 ./Fifo_read 

新建一个终端,在新建的终端中输入  ./Fifo_write hello_Fifo

这样就可以实现在两个不是父子进程关系的进程中同时使用命名管道,并实现命名管道的读写。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值