进程间通信(IPC)——FIFO(命名管道)

FIFO,也称为命名管道,它是一种文件类型。

特点:

        1. FIFO可以在无关的进程之间交换数据,与无名管道不同。

        2. FIFO有路径名与之相关联,它以一种特殊设备文件形式存在于文件系统中。

原型:

SYNOPSIS
       #include <sys/types.h>
       #include <sys/stat.h>

       int mkfifo(const char *pathname, mode_t mode);
/*
RETURN VALUE
       On  success mkfifo() and mkfifoat() return 0(成功返回0).  In the case of an error,
       -1(失败返回-1) is returned (in which case, errno is set appropriately).
*/

其中的 mode 参数与open函数中的 mode 相同。一旦创建了一个 FIFO,就可以用一般的文件I/O函数操作它。

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

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

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

代码示例:

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

write.c

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

int main()
{
        int fd = 0;
        int cnt = 0;
        char *str = "hello from write";
        if((fd = open("./file1",O_WRONLY)) == -1) //以只写方式打开FIFO文件
        {
                printf("open file1 failed\n");
        }else
        {
                printf("open file1 success\n");
        }
        while(1)
        {
                cnt++;
                write(fd,str,strlen(str));        //写到FIFO中
                sleep(1);           //休眠一秒再写
                if(cnt == 5)        //写五次
                {
                        break;
                }
        }
        close(fd);    //关闭FIFO文件
        return 0;
}

read.c

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

int main()
{
        int fd = 0;
        int nread = 0;
        char buf[16];
        if((mkfifo("./file1",0600)) == -1 && errno != EEXIST)//创建FIFO管道
        {
                printf("creat fifo failed\n");
                perror("reason");
        }
        if((fd = open("./file1",O_RDONLY)) == -1)    //以只读方式打开FIFO文件
        {
                printf("open file1 failed\n");
        }
        while((nread = read(fd,buf,16)) > 0)    //读内容
        {
                printf("read %d byte,context:%s\n",nread,buf);
        }
        close(fd);    //关闭FIFO文件
        return 0;
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

牵猫散步的鱼儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值