Unix/Linux进程间通信——FIFO

本文介绍了FIFO(First In, First Out),又称有名管道,在Unix/Linux系统中的使用方法及特点。包括如何通过mkfifo和mknod创建FIFO,如何使用open、read、write等函数与FIFO进行交互,以及在不同进程间进行通信的例子。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

FIFO("First In, First Out"),有时也被称为有名管道,管道只能在父进程和子进程或兄弟进程之前进行通信,而FIFO则无此限制,即可以在任意进程之间进行通信。

Unix/Linux中,可以使用mkfifo和mknod来创建FIFO,原型如下:
#include <sys/types.h>
#include <sys/stat.h>

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

int mknod(const char *path, mode_t mode, dev_t dev);
创建了FIFO之后,就可以使用open函数来打开它(一般的IO函数都可用于FIFO: open、close、read、write等,就如同普通的文件一样)。

FIFO的实例如下:
/* writer.c */
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <unistd.h>

int main()
{
        int fd;
        char * myfifo = "/tmp/myfifo";

        /* create the FIFO (named pipe) */
        mkfifo(myfifo, 0666);

        /* write "Hi" to the FIFO */
        fd = open(myfifo, O_WRONLY);
        write(fd, "Hi", sizeof("Hi"));
        close(fd);

        /* remove the FIFO */
        unlink(myfifo);

        return 0;
}

/* reader.c */
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <unistd.h>

#define MAX_BUF 1024

int main()
{
        int fd;
        char * myfifo = "/tmp/myfifo";
        char buf[MAX_BUF];

        /* open, read, and display the message from the FIFO */
        fd = open(myfifo, O_RDONLY);
        read(fd, buf, MAX_BUF);
        printf("Received: %s\n", buf);
        close(fd);

        return 0;
}
在打开一个FIFO时,如果不指定O_NONBLOCK标志,则只读open阻塞直到某个进程以写方式打开FIFO;同样,只写open阻塞直到其它进程以读方式打开FIFO。
如果指定了O_NONBLOCK标志,则只读open立即返回;同样只写open出错返回-1,其errno值为ENXIO。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值