无名管道实现进程间的通信

从管道中读数据的特点:
1、默认用read函数从管道中读数据是阻塞的。
2、调用write函数向管道里写数据,当缓冲区已满时write也会阻塞。
3、通信过程中,读端口全部关闭后,写进程向管道内写数据时,写进程会(收到SIGPIPE信号)退出。

注意:
利用无名管道实现进程间的通信,都是父进程创建无名管道,然后再创建子进程,子进程继承父进程的无名管道的文件描述符,然后父子进程通过读写无名管道实现通信。

案例代码:

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<signal.h>
#include<unistd.h>
int main()
{
        //创建无名管道
        int pipefd[2];
        if(pipe(pipefd) == -1)
        {
                perror("fail to pipe");
                exit(1);
        }

        //使用fork函数创建子进程
        pid_t pid;
        pid = fork();
        if(pid <0)
        {
                perror("fail to fork");
                exit(1);
        }

        else if(pid > 0)
        {
                char buf[128] = {};
                while(1)
                {
                        fgets(buf,sizeof(buf),stdin);
                        buf[strlen(buf)-1] = '\0';

                        if(write(pipefd[1],buf,sizeof(buf)) == -1)
                        {
                                perror("fail to write\n");
                                exit(1);
                        }
                }
        }

        else
        {
                char buf[128] = "";
                while(1)
                {
                        if(read(pipefd[0],buf,sizeof(buf)) == -1)
                        {
                                perror("fail to read\n");
                                exit(1);
                        }

                        printf("from parent: %s\n",buf);


                }

        }

        return 0;
}

运行结果:
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值