进程间通信--命名管道(fifo)

区别于无名管道,只有文件描述符,只能用于父子进程的通信。
有名管道(fifo)其通信过程通过文件系统,可以达到不同进程中的通信
函数原型:

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

int mkfifo(const char *pathname, mode_t mode);
  • 参数1为fifo的文件路径
  • 参数2为所创建fifo的umask(文件掩码)

在程序中调用了mkfifo后,就可以像正常文件一样的对其进行读写


  1. 当在当前目录fifo文件存在时,mkfifo()返回-1 errno返回EEXIST
  2. 当管道文件被打开后,只有读端,或者只有写端时,进程将被堵塞open可以加上O_NONBLOCK 这样就是非阻塞式读写
  3. 引用一句话,之前学习时没怎么看懂逻辑,自己code了一遍就懂了不少

FIFO的打开规则:
如果当前打开操作时为读而打开FIFO时,若已经有相应进程为写而打开该FIFO,则当前打开操作将成功返回;否则,可能阻塞到有相应进程为写而打开该FIFO(当前打开操作设置了阻塞标志);或者,成功返回(当前打开操作没有设置阻塞标志)。
如果当前打开操作时为写而打开FIFO时,如果已经有相应进程为读而打开该FIFO,则当前打开操作将成功返回;否则,可能阻塞直到有相应进程为读而打开该FIFO(当前打开操作设置了阻塞标志);或者,返回ENIO错误(当期打开操作没有设置阻塞标志)。

demo :

#ifdef WR

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


#define BUF_SIZE 64

int main(int argc, char const *argv[])
{
    int fd = -1;
    int ret = -1;
    const char word[] = {"hello world!"};
    char buf[64];

    memset(buf, 0, sizeof(buf));
    ret = mkfifo("./fifo", 0666);
    if(ret < 0){
        perror("fifo");
        return -1;
    }


    fd = open("./fifo", O_WRONLY);
    if(fd < 0){
        perror("open");
        return -1;
    }

    write(fd, word, sizeof(word));

    printf("%s\n", "message send");

    pause();



    return 0;
}




#elif RD

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

#include <unistd.h>
#include <stdio.h>
#include <errno.h>
#include <string.h>

#define BUF_SIZE 64

int main(int argc, char const *argv[])
{
    int fd = -1;
    int ret = -1;
    char buf[64];

    memset(buf, 0, sizeof(buf));
    fd = open("./fifo", O_RDONLY);
    if(fd < 0){
        perror("open");
        return -1;
    }

    read(fd, buf, BUF_SIZE);
    printf("%s\n", buf);

    printf("%s\n", "message get");

    pause();

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值