进程通信之无名pipe

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/fr555wlj/article/details/78272960

1.创建一个管道 使用pipe()函数
pipe系统调用需要打开两个文件
这里写图片描述

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

int main()
{
        int pipe_fd[2];
        if(pipe(pipe_fd)<0)  //pipe_fd =0;
        {
        printf("pipe create error\n");
        return -1;
        }
        else
                printf("pipe create success\n");
        close(pipe_fd[0]);
        close(pipe_fd[1]);
}

运行无错误应显示:

 ./pipe
pipe create success

2.父子管道通信
这里写图片描述

#include <unistd.h>
#include <sys/types.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>

int main()
{
        int pipe_fd[2];//管道文件
        pid_t pid; //子进程
        char buf_r[100]; //字节
        char* p_wbuf; //数组指针
        int r_num;

    //memset函数用来初始化数组(数组名,初始化量,长度)
        memset(buf_r,0,sizeof(buf_r));

        //判断管道是否建立成功
        if(pipe(pipe_fd)<0)
        {
                printf("pipe create error\n");
                return -1;
        }

        if((pid=fork())==0)  //判断是否是子进程
        {
                printf("\n");
                //关闭写管道,然后挂起
                close(pipe_fd[1]);
                sleep(2);
                //读取管道信息read(文件名,数组形式?长度)
                if((r_num=read(pipe_fd[0],buf_r,100))>0)
                {
                        printf(   "%d numbers read from the pipe is %s\n",r_num,buf_r);
                }
                close(pipe_fd[0]);
                exit(0);
        }
        else if(pid>0)
        {
            //关闭读管道,然后向管道写入信息,然后挂起
                close(pipe_fd[0]);
                if(write(pipe_fd[1],"Hello",5)!=-1)
                        printf("parent write1 Hello!\n");
                if(write(pipe_fd[1]," Pipe",5)!=-1)
                        printf("parent write2 Pipe!\n");
                close(pipe_fd[1]);
                sleep(3);

        printf("it is all done");
                waitpid(pid,NULL,0); /**/
                exit(0);
        }
        return 0;
}

运行如下:


root@ubuntu:/home/14-dianxin/simple-study-code/process-communication-study# ./pipe_rw
parent write1 Hello!
parent write2 Pipe!

10 numbers read from the pipe is Hello Pipe
it is all done

猜你喜欢

转载自blog.csdn.net/fr555wlj/article/details/78272960
今日推荐