进程间通信之命名管道

命名管道(FIFO)是进程间通信的一种方式。

API:

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

DEMO:

// 写进程
int main(int argc, char **argv) {
    char filename[] = "/tmp/my_fifo";
    if (mkfifo(filename, 0777) < 0) {
        perror("mkfifo error");
        exit(1);
    }
    int fd = open(filename, O_WRONLY);
    char buffer[128] = "hello world";
    write(fd, buffer, strlen(buffer));
    printf("write done\n");
    return 0;
}

// 读进程
int main(int argc, char **argv) {
    char filename[] = "/tmp/my_fifo";
    int fd = open(filename, O_RDONLY);
    char buffer[128];
    int n = read(fd, buffer, 128);
    buffer[n] = '\0';
    printf("input is : %s\n", buffer);
    return 0;
}

两个地方需要注意:

1. mkfifo会在/tmp目录下创建文件my_fifo

2. 读进程open之前,写进程被阻塞

   (it has to be open at both ends simultaneously before you can proceed to do any input or output operations on it.)

 

管道相比,命名管道可用于任意两个进程间的通信。

posted @ 2017-03-14 11:21  Sawyer Ford  阅读(222)  评论(0编辑  收藏  举报