进程间通信之命名管道

命名管道(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.)

 

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

转载于:https://www.cnblogs.com/gattaca/p/6547580.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值