Linux系统编程——fifo命名管道

定义

fifo也被称为命名管道。未命名的管道只能在两个相关的进程之间使用,而且这两个进程还有一个共同的创建了他们的祖先进程,但是fifo,不相关的进程也能交换数据。

fifo的创建

fifo是一种文件类型,fifo的创建有两种方式。
1.直接用命令创建 mkfifo
2.利用函数创建

int mkfifo(const char *pathname,mode_t,mode)

下面用一个案例演示从一个进程发送数据到另外一个不相干的进程。

发送端:

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <fcntl.h>
#include <string.h>

void sys_err(const char *str)
{
  perror(str);
  exit(1);
}

int main()
{
  int fd,len,i;
  char buf[4096];

  fd=open("./10_myfifo",O_WRONLY);
  if(fd<0)
  {
    sys_err("open error");
    exit(1);
  }

  i=0;
  while(1)
  {
    sprintf(buf,"hello fifo%d\n",i++);
    write(fd,buf,strlen(buf));
    sleep(1);
  }
  close(fd);
  return 0;
}

接收端:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>

void sys_err(const char *str)
{
  perror(str);
  exit(1);
}

int main()
{
  int len;
  char buf[4096];
  int fd=open("./10_myfifo",O_RDONLY);
  if(fd==-1)
  {
    sys_err("open error");
  }
  while(1)  //循环将读取的数据写到平面镜上去
  {

    len=read(fd,buf,sizeof(buf));
    if(len<0)
    {
      sys_err("read error");
      exit(1);
    }
    write(STDOUT_FILENO,buf,len);
  }
  return 0;
}

打开两个终端一个运行写端,另一个运行读端,在读端会将接收到的数据输出到屏幕上,如下所示
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值