进程间通信之有名管道

2019-06-28  本文已影响0人  Jake_Yang

1 有名管道

有名管道与无名管道的通信机制差不多,唯一不同在于,有名管道需要在文件系统中创建指定名称的管道文件,用于通信。
一旦创建好一个有名管道文件,任何进程都可以打开该文件,并进行读写操作。因此有名管道可以用在无父子关系的进程间通信。

2 接口

2.1 创建

Linux下使用mkfifo接口来创建管道文件,接口原型如下。

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

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

2.2 打开、关闭及读写操作

有名管道的打开、关闭及读写操作与普通文件,采用open、close、write、read等系统文件操作接口来操作管道。
在操作有名称管道时,需要注意:

3 示例

3.1 发送程序

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

int main(int argc, char **argv)
{
    if (mkfifo("/tmp/fifo", 0666) < 0) {
        printf("make fifo failed\n");
        return -1;
    }
    int fd = ::open("/tmp/fifo", O_WRONLY);
    if (fd < 0) {
        printf("Open fifo file failed\n");
        return -1;
    }
    ::write(fd, "Hello", 6);
    ::close(fd);
    return 0;
}

3.2 接收程序

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
#include <unistd.h>
int main(int argc, char **argv)
{
    int fd = ::open("/tmp/fifo", O_RDONLY);
    if (fd < 0 ) {
        printf("%s(%s[%d]): watcher init failed", __FILE__, __func__, __LINE__);
        return;
    }

    char msg[6];
    ::read(fd,  msg, 6);
    printf("receive message: %s\n", msg);
    return 0;
}
上一篇 下一篇

猜你喜欢

热点阅读