Linux pipe()系统调用示例

Linux系统调用pipe函数,创建一个pipe,通过传入的fd数组返回pipe的读、写两端。
其中fd[ 0 ]用于读,fd[ 1 ]用于写。
一个pipe是单向数据传输的,不用用于父子进程双向读写。创建2个pipe实现父子进程间的双线读写。

#include <unistd.h>
#include <stdio.h>
#include <wait.h>

int main() {
    int fds1[2];
    int fds2[2];

	// fds[0]用于读,fd[1]用于写
	// 这里创建2个pipe
    pipe(fds1);
    pipe(fds2);

    printf("fds1: %d, %d\n", fds1[0], fds1[1]);
    printf("fds2: %d, %d\n", fds2[0], fds2[1]);

	// 创建子进程
    pid_t pid = fork();

    if (pid > 0) {
    // 父进程
		// 关闭2个pipe中不需要的文件描述符
        close(fds1[0]);
        close(fds2[1]);

        printf("parent: %d: parent process (child: %d)\n", getpid(), pid);

        char s[128];
        sprintf(s, "from parent(%d), to child(%d)", getpid(), pid);
        write(fds1[1], s, sizeof(s));

        char buf2[80];
        read(fds2[0], buf2, sizeof(buf2));
        printf("parent: receive: %s\n", buf2);

        close(fds1[1]);
        close(fds2[0]);
    } else if(pid == 0) {
    // 子进程
		// 关闭2个pipe中不需要的文件描述符
		close(fds1[1]);
        close(fds2[0]);

        printf("child: %d: child process, parent(%d)\n", getpid(), getppid());

        char buf1[80];
        read(fds1[0], buf1, sizeof(buf1));
        printf("child: receive: %s\n", buf1);

        char s[128];
        sprintf(s, "to parent(%d), from child(%d)", getppid(), getpid());
        write(fds2[1], s, sizeof(s) );

        close(fds1[0]);
        close(fds2[1]);
    }

    waitpid(pid, NULL, 0);
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

抓饼先生

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

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

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

打赏作者

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

抵扣说明:

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

余额充值