Unix/Linux进程间通信——FIFO

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。

你可能感兴趣的:(Unix/Linux进程间通信——FIFO)