进程间通信->有名管道

FIFO:命名管道,它是一种文件类型。
1、特点
FIFO可以在无关的进程之间交换数据
FIFO有路径名与之相关联,以一种特殊设备文件形式存在于文件系统中。
2、原型
#include <sys/stat.h>
int mkfifo(const char *pathname, mode_t mode);
参数:
pathname:文件路径
mode:与open的mode相同,mkfifo创建的文件可以用read,write进行传入传出数据
返回值:成功返回0,出错返回-1

当 open 一个FIFO时,是否设置非阻塞标志(O_NONBLOCK)的区别:

若没有指定O_NONBLOCK(默认),只读 open 要阻塞到某个其他进程为写而打开此 FIFO。类似的,只写 open 要阻塞到某个其他进程为读而打开它。

若指定了O_NONBLOCK,则只读 open 立即返回。而只写 open 将出错返回 -1 如果没有进程已经为读而打开该 FIFO,其errno置ENXIO。

3、例子
FIFO的通信方式类似于在进程中使用文件来传输数据,只不过FIFO类型文件同时具有管道的特性。在数据读出时,FIFO管道中同时清除数据,并且“先进先出”。下面的例子演示了使用 FIFO 进行 IPC 的过程:

read.c

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <unistd.h>
int main()
{
    char buf[1024] = {0};
    if(mkfifo("./fail1",0666) && errno !=  EEXIST)
    {
        perror("why");
    }
    int fd = open("./fail1",O_RDONLY);
    printf("this is read\n");
    while(1)
    {
           read(fd,buf,1024);
           printf("buf is %s\n",buf);
    }
    close(fd);
    return 0;
}

write.c

#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>
int main()
{
    char *writebuf = "hello chm";
    int fd = open("./fail1",O_WRONLY);
    printf("this is write\n");
    while(1)
    {
           sleep(1);
           write(fd,writebuf,strlen(writebuf));
           printf("writebuf is %s\n",writebuf);
    }
    close(fd);
    return 0;
}

结果:
在这里插入图片描述

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值