linux 创建并使用 无名管道 / 有名管道

父进程 通过 fork() 的方式 把管道的读端和写端传递给 子进程 

#include <stdio.h>
#include "stdlib.h"
#include "unistd.h"

int main() {

    int fd[2];

    if (pipe(fd) < 0) {
        perror("Fail to create pipe");
        exit(EXIT_FAILURE);
    }

    /**
     *  create child process (Linux):
     *      parent_process's pid is child PID
     *      child_process's  pid is 0
     */
    pid_t pid = fork();
   // start two process from this line

    if (pid == -1) {
        perror("fork error");
        exit(EXIT_FAILURE);
    }
    // If child process: close read port
    if (pid == 0) {
        close(fd[0]);
        // 管道:传送的是 无格式字节流
        write(fd[1], "hello parent", 12);
        exit(EXIT_SUCCESS);
    }
    // parent process: close write port
    close(fd[1]);
    char buf[20] = {0};
    read(fd[0], buf, 20);
    printf("receive data = %s\n", buf);

    return 0;
}

创建 有名管道 

#include "stdio.h"
#include "sys/types.h"
#include "sys/stat.h"

int main() {

    int res;
    res = mkfifo("../aaa", 0644);

    if (res < 0) {
        printf("create fifo failure\n");
        return -1;
    }
    printf("create fifo success\n");

    return 0;
}

 有名管道 写入数据 

#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"
#include "string.h"

int main() {

    // use fifo: write
    char arr[] = "hello fifo !!!";
    int fd = open("../aaa", O_WRONLY);
    if (fd == -1) {
        printf("open write failure\n");
    }
    write(fd, arr, strlen(arr));

    return 0;
}

有名管道 读出数据

#include "stdio.h"
#include "unistd.h"
#include "sys/types.h"
#include "sys/stat.h"
#include "fcntl.h"

int main() {

    // use fifo: read
    char buf[30];
    int fd = open("../aaa", O_RDONLY);
    if (fd == -1) {
        printf("open read failure\n");
    }
    int len = read(fd, buf, sizeof(buf));
    write(STDOUT_FILENO, buf, len);

    return 0;
}

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

beOkWithAnything

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值