Linux进程间的通信(2)--------无名管道

在代码界一直流行着这么一句话,“Linux 一切皆文件!”
所以文件IO的读写是 非常非常重要的!接下来为大家介绍一种Linux间的通信方式---------------无名管道
在Linux里面已经规定0位输入(stdin),1位输出(stdout), 2为错误(stderror)
例如用无名管道申请的文件描述符是从3开始的, 0 1 2被系统占用了

#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
        int fd[2];
        int ret=pipe(fd);
        if(ret!=0)
        {
                printf("creat pipe is faile !\n");
                exit(1);
        }
        printf("fd[0]=%d       fd[1]=%d    !\n",fd[0],fd[1]);






        return 0;
}    

在这里插入图片描述
下面为大家写一段无名管道读写的代码,以便大家理解:

#include <unistd.h>
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
        int fd[2];
        int ret=pipe(fd);//创建无名管道
        char *buf="Mr.Qin";//缓存区
        if(ret!=0)
        {
                printf("creat pipe is faile !\n");
                exit(1);
        }
        write(fd[1],buf,sizeof(buf));
        read(fd[0],buf,128);
        printf("\nThe buf data is    %s\n",buf);



        return 0;
}    

在这里插入图片描述
无名管道就像一个队列一样,只能在一端进行读或者写
在这里插入图片描述
其次,pipe无名管道只能用于有亲缘关系的进程通信

#include"stdio.h"
#include"sys/types.h"
#include"stdlib.h"
int main()
{
        pid_t pid;

        int fd[2],ret;
        ret=pipe(fd);//      注意pipe()只能写在fork()函数之前,不然将在不同的进程创立两个不同的管道,读写管道不能同步
        if(ret!=0){
                printf("creat pipe faile!\n");
                exit(1);
        }
    
        pid=fork();
        int process_inter=0;
        if(pid==0)//child processes
        {
        read(fd[0],&process_inter,sizeof(process_inter));//子进程可以读到
        while(process_inter==0);
        int i=0;
        for(;i<5;i++)
                {
                        printf("\nI am child process !      %d\n",i);
                }
                usleep(100);
        }
        else if(pid>0)//parent  processes
        {
        int i=0;
        for(;i<5;i++)
                {
                        printf("\nI am parent process !      %d\n",i);
                }
                process_inter=1;
                write(fd[1],&process_inter,sizeof(process_inter));//在父进程写
                usleep(100);
        }
        else
{
        printf("\nprocess request faile!\n");
}
        while(1);
        return 0;
}

在这里插入图片描述

但是,不具有亲缘关系的进程,就不可以用无名管道进行通信,就要用下一章要介绍的有名管道来处理!

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值