进程间通信(IPC)之 有名管道

有名管道也就命名管道

函数原型

#include <sys/types.h> 
 
#include <sys/stat.h> 
 
int mkfifo(const char *filename,mode_t mode);

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

mode则指定了文件的读写权限。

有名管道也被称为FIFO文件,是一种特殊的文件。由于linux所有的事物都可以被视为文件,所有对有名管道的使用也就变得与文件操作非常统一。

例子

创建有名管道

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

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


int main()
{
        if(mkfifo("./file", 0600) == -1 && errno == EEXIST){
                printf("mkfifo fail\n");
                perror("why");
        }else{
                if(errno == EEXIST){
                        printf("file you\n");
                }else{
                        printf("mkfifo success\n");
                }
        }

        return 0;
}

有名管道特点:

  1. 有名字,存储于普通文件系统中

  1. 任何具有相应权限的进程都可以使用open()来获取FIFO的文件描述符

  1. 跟普通文件一样,用read()和write()来读和写

  1. 不能用lseek()来定位

  1. 具有写入原子性,支持多写者同时进行操作而数据不会互相践踏

创建有名管道还可以省略写成

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

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


int main()
{
        if(mkfifo("./file", 0600) == -1 && errno != EEXIST){
                printf("mkfifo fail\n");
                perror("why");
        }

        return 0;
}

打开有名管道

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

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

现在分两个文件,一个用于写,一个用于读

读:

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

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


int main()
{
        char buf[30] = {0};
        int n_read = 0;

        if(mkfifo("./file",0600) == -1 && errno != EEXIST){
                printf("mkfifo faill\n");
        }
        int fd = open("./file",O_RDONLY);
        printf("write open success\n");
        
        n_read = read(fd, buf, 30);
        printf("read %d byte from fifo, context :%s\n",n_read, buf);
        
        close(fd);

        return 0;
}

写:

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

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


int main()
{
        int cnt = 0;
        char *str = "message from fifo";

        int fd = open("./file",O_WRONLY);
        printf("write open success\n");

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

        return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值