有名管道的概念及创建及使用

有名管道的概念及创建及使用

1概念:它是一种文件类型,在文件系统中可以看到。程序中可以查看文件stat结构中st_mode成员的值来判断文件是否是FIFO文件。创建一个FIFO文件类似于创建文件,FIFO文件就像普通文件一样。FIFO中可以很好地解决在无关进程间数据交换的要求,并且由于它们是存在于文件系统中的,这也提供了一种比匿名管道更持久稳定的通信办法。

FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据。在shell中mkfifo命令可以建立有名管道,下面通过一个实例来帮助读者理解FIFO。

2有名管道编程实战:
有名管道一般用的多的是令其堵塞,因而在创建管道后开始读取时,需要另一进程进行写,才能正确读取到。
创建有名管道编程及写入数据:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>


int main()
{
        int fd;

        int n_write;

        int cnt;

        cnt=0;

        char *str="wencai love pingping";//要发送的数据,可自己决定

        fd=open("./file1",O_WRONLY);

        printf("open sucesess\n");

        while(1){
                n_write=write(fd,str,strlen(str));
                sleep(1);
                cnt++;
                if(cnt==4){
                        break;
                        }
                }

        close(fd);

        return 0;

}

读取管道中的数据:

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>


int main()
{
        int fd;

        int n_read;

        int cnt=0;

        char buf[30]={0};

        if((mkfifo("./file1",0600)==-1)&&errno!=EEXIST){  //查看是否有创建成功的管道
                printf("creat failuer\n");
                perror("why");
                }

        fd=open("./file1",O_RDONLY);

        printf("open sucesess\n");

        while(1){
                memset(buf,'\0',sizeof(buf));//清空收到的消息
                n_read=read(fd,buf,30);//读取管道中的数据
                printf("read %d byte from,context:%s\n",n_read,buf);
                if(cnt++==4){
                        break;
                        }
        }

        close(fd);

        return 0;

}

然后我们来看看运行后的效果
在这里插入图片描述

运行程序后,可以看到字符串被传递了过去,从而通过有名管道实现了进程间的通信。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值