Linux C进程间通信之pipe

3 篇文章 0 订阅
// 多进程以及ipc管道方式进程间通信
/*
1、父进程调用pipe开辟管道,得到两个文件描述符指向管道的两端。
2、父进程调用fork创建子进程,那么子进程也有两个文件描述符指向同一管道。
3、父进程关闭管道读端,子进程关闭管道写端。父进程可以往管道里写,子进程可以从管道里读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通
*/
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>

#define MAX_LINE 256 // 读数据最大长度

int main(void) {
    printf("Run at process id: %d!\n\n", getpid());

    int fd[2];  // 管道端口,fd[0]读端口,fd[1]写端口
    int channel = pipe(fd);  // 创建管道
    if (channel < 0) {
        printf("error: make ipc channel fail!\n");
        exit(1);
    }

    pid_t pid = fork();  // 创建子进程
    if (pid < 0) {
        printf("error: child process fork fail!\n");
        exit(1);
    }

    if (pid == 0) { // 子进程
        char message[] = "Hello father, im your son!\n"; // 待发送数据
        printf("Child process %d send to parent: %s\n", getpid(), message);
        close(fd[0]); // 关闭读端口
        write(fd[1], message, sizeof(message) / sizeof(message[0])); // 写数据到写端口
        sleep(2); // 模拟发送时间2秒
    } else { // 父进程
        waitpid(pid, NULL, 0); // 等待子进程信号
        close(fd[1]); // 关闭写端口
        char message[MAX_LINE]; // 定义接受数据数组
        read(fd[0], message, MAX_LINE); // 读端口读取数据
        printf("Parent process %d read from %d: %s\n", getpid(), pid, message);
    }
    return 0;
}

 执行结果:

root@DESKTOP-L8AO2MP:/mnt/g/c/test/process# ./a.out
Run at process id: 962!

Child process 963 send to parent: Hello father, im your son!

Parent process 962 read from 963: Hello father, im your son!

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值