C语言父子进程匿名管道通信

友链

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <string.h>
#include <sys/wait.h>
int main(int argc, char *argv[])
{

    /*

   #include <unistd.h>

      On Alpha, IA-64, MIPS, SuperH, and SPARC/SPARC64; see NOTES
       struct fd_pair {
           long fd[2];
       };
       struct fd_pair pipe();

     On all other architectures
       int pipe(int pipefd[2]);
        pipefd数组,0对应读,1对应写
        返回值为0代表成功,-1代表失败
        匿名管道只能用于具有血缘关系的进程间通信
        管道默认是阻塞的,如果读不到数据,就会阻塞,直到管道中有数据
       #define _GNU_SOURCE            See feature_test_macros(7)

    */
    // 子进程发送数据给父进程,父进程读取到数据之后输出
    pid_t pid;
    //在fork之前,先创建匿名管道
    int pidfd[2];
    int ret = pipe(pidfd);
    if (ret == -1)
    {
        perror("pipe");
        exit(0);
    }
    pid = fork();
    if (pid > 0)
    { //从管道读取数据
        printf("PARENT pid: %d\n", getpid());

        char buf[1024] = {0};
        while (1)
        {
            int len = read(pidfd[0], buf, sizeof(buf));
            printf("PARENT receive :%s, pid: %d\n", buf, getpid());

            char *str = "wo shi ni die";
            write(pidfd[1], str, strlen(str));
            sleep(1);
        }
    }
    else if (pid == 0)
    {
        // sleep(3);
        printf("CHILD pid: %d\n", getpid());
        char buf[1024] = {0};
        //往管道写数据
        while (1)
        {

            char *str = "cao ni ma";
            write(pidfd[1], str, strlen(str));
            sleep(1);

            int len = read(pidfd[0], buf, sizeof(buf));
            printf("CHILD receive :%s, pid: %d\n", buf, getpid());
        }
    }

    // printf("PARENT receive :%s, pid: %d\n", buf, getpid());}

    return 0;
}
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值