管道通信

常见的通信方式:单工(广播),半双工(对讲机),全双工(电话)
管道:半双工通信

管道函数:
int pipe(int pipefd[2]);
pipefd读写文件描述符,0代表读,1代表写
返回值:失败返回-1,成功返回0

pipe.c

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

int main(int argc,char *argv[])
{
    int fd[2];
    pipe(fd);
    pid_t pid=fork();

    if(pid==0){
        sleep(3);
        close(fd[0]);
        write(fd[1],"hello",5);    
        while(1){
            sleep(1);
        }
    }else if(pid>0){
        char buf[12]={0};
        close(fd[1]);
        close(fd[0]);
        wait(&status);
        if(WIFSIGNALED(status)){
            printf("killed by %d\n",WTERMSIG(status));
        }
        while(1){
            sleep(1);
        }
        while(1){
            int ret=read(fd[0],buf,sizeof(buf));
            if(ret==0){
                printf("read over\n");
                break;
            }
            if(ret>0){
                write(STDOUT_FILENO,buf,ret);
            }
    }
    return 0;
}

父子进程实现pipe通信,实现ps aux|grep bash功能

pipe_ps.c

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

int main(int argc,char *argv[])
{
    int fd[2];
    pipe(fd);
    pid_t pid=fork();

    if(pid==0){
        //关闭读端
        close(fd[0]);
        dup2(fd[1],STDOUT_FILENO);  //标准输出重定向到管道写端
        execlp("ps","ps","aux",NULL);  
    }else if(pid>0){   
        //关闭写端     
        close(fd[1]);
        dup2(fd[0],STDIN_FILENO); //标准输入重定向到管道读端
        execlp("grep","grep","bash",NULL);  
    }
    return 0;
}

读管道:
写端全部关闭–read读到0,相当于读到文件末尾
写端没有全部关闭 有数据–read读到数据
没有数据–read阻塞 fcntl函数可以更改非阻塞
写管道:
读端全部关闭–产生一个信号SIGPIPE,程序异常终止
读端没有全部关闭 管道已满–write阻塞 (读端一直不读,写端持续写入)
管道未满–write正常写入

计算管道大小
long fpathconf(int fd,int name);

管道的优点:简单
管道的缺点:只能有血缘关系的进程通信;
父子进程单向通信,如果需要双向通信,需要创建多根管道

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

给算法爸爸上香

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

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

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

打赏作者

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

抵扣说明:

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

余额充值