linux C/C++ 进程间通信之父子进程通过无名管道通信【002】

1:vim parentnoname.c

#include<stdio.h>
#include<stdlib.h>
#include<string.h>

#include<unistd.h>
#define SIZE 64
int main(void)
{
        int fd[2];
        pid_t pid=-1;
        int ret=-1;
        char buf[SIZE];


        //创建无名管道
        ret=pipe(fd);
        if(-1==ret)
        {
                perror("pipe");
                return 1;
        }

        pid=fork();
        if(-1==pid)
        {
                perror("fork");
                return 1;
        }

        //子进程
        if(0==pid)
        {
                close(fd[1]);
                memset(buf,0,SIZE);
                //读管道
                ret=read(fd[0],buf,SIZE);
                if(ret<0)
                {
                        perror("read");
                        exit(-1);
                }
                printf("child process buf:%s\n",buf);
                close(fd[0]);

                exit(0);
        };
        //父进程
        close(fd[0]);
        ret=write(fd[1],"abcdefghijk",10);
        if(ret<0)
        {
                perror("write");
                return 1;
        }

        printf("parent process write len:%d\n",ret);

        close(fd[1]);
        return 0;

}


版权声明:本文为weixin_38818512原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。