pipe函数管道的相关代码讲解

#include <string.h>
#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/wait.h>
#define MSG "Hello,this is test!!!"

int main()
{

        int      pipe_p[2];
        int      rv=-1;
        pid_t    pid;
        char     buf[1024];
        int      wstatus;


        if(pipe(pipe_p)<0)
        {
                printf("Pipe is failure:%s\n",strerror(errno));
                return -1;
        }

        if((pid=fork())<0)
        {
                printf("Fork() child failure:%s\n",strerror(errno));
                return -2;
        }

        else if(pid==0)
        {
                printf("This is child\n");
                memset(buf,0,sizeof(buf));
                close(pipe_p[1]);//1 is write
                rv=read(pipe_p[0],buf,sizeof(buf));
                if(rv<0)
                {
                        printf("Read failure:%s\n rv=%d\n",strerror(errno),rv);
                        return -3;
                }
                printf("Read data %d bytes from father:%s\n",rv,buf);

                return 0;
        }

        close(pipe_p[0]);
        if((rv=write(pipe_p[1],MSG,strlen(MSG)))<0)
        {
                printf("Write failure:%s\n",strerror(errno));
                return -4;
        }
         printf("Parent start wait child process exit...\n");
          wait(&wstatus);


        return 0;
}

pipe函数会创建一个管道,其中fd[1]为写入数据,fd[0]为读取数据,该管道相当于一个缓冲区域,读取之后数据将不在存在。

 

 

 在创建子进程之后,子进程会复制父进程的所有代码,包括起创建的fd[0],fd[1],所有这时有四个fd,要使用管道需要关闭不相关的fd才能运行。例如父进程要向子进程里写入数据,需要关闭父进程的fd[0]和关闭子进程的fd[1],让管道中仅存在一条线。

 此外,使用wait函数是因为不能让父进程在子进程之前结束,wait用于等待子进程结束,回收并释放子进程资源

我们是在父进程中使用wait(),可以不让父进程先于其产生的子进程结束,因为如果父进程结束了,而子进程还没有结束,那这个进程就会变成一个“孤儿进程”,他会被init进程收养(进程号为1),并由init进程对它们完成状态收集工作。

当然如果子进程结束了,但是父进程没有调用wait或waitpid,那么子进程的资源就无法得到收集释放,这时候的子进程被称为“僵尸进程”,会占用系通资源,是非常不好的,危害很大

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值