IPC(一)---------匿名管道

一、管道的分类

          管道分为匿名管道命名管道

         匿名管道

         (1)、在关系进程中进行(父进程和子进程、兄弟进程之间)

         (2)、由pipe系统调用,管道由父进程建立。

         (3)、 管道位于内核空间、其实是一块缓存。

        命名管道:

        (1)、任何两个进程间都可通过命名管道进行数据传输。

        (2)、通过系统调用mkfifo创建。

       (3)、本质是内核中的一块缓存,另外在文件系统中以一个特殊的设备文件(管道文件)存在。

二、本篇主要讲匿名管道:

      管道创建:

       #include <unistd.h>

       int pipe(int fd[2]);

       返回: 成功返回0,出错返回-1;

       fd[0]: 为pipe的读端

       fd[1]:为pipe的写端

三、管道创建和读写代码:

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>

#include <stdlib.h>



int main()
{
    int fd[2];
    pid_t pid;



    //管道创建成功后,fd[0]是读管道,fd[1]是写管道
    if(pipe(fd) < 0)
    {
        printf("pipe error\n");

        exit(-1);
    }



    if((pid = fork())< 0)
    {
        printf("fork error\n");

        exit(-1);
    }

    if(pid == 0)//子进程
    {

        close(fd[0]);//子进程关掉读管道
        printf("child process\n");
        
        int start = 1,end = 100;

        write(fd[1],&start,sizeof(start));
        write(fd[1],&end,sizeof(end));

        exit(0);
    }
    else
    {
        printf("parent child\n");
        close(fd[1]);//父进程关掉写管道
        
        int start = 0,end = 0;

        read(fd[0],&start,sizeof(start));
        read(fd[0],&end,sizeof(end));

        printf("start=%d,end=%d\n",start,end);

        exit(0);
    
    }




    return 0;

}

运行结果:

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

KiranWang

一起努力

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

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

打赏作者

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

抵扣说明:

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

余额充值