进程通讯中的无名管道

1,无名管道的建立

#include <unistd.h>

int pipe(int pipefd[2]);

    返回值:成功返回0,失败返回-1,并且可以通过perror把错误码打印出来。

2,用法

    1) 创建管道 pipe。
    2)关闭无关的端口。(本身是全双工的,但是我们两个进程用一个管道通讯,会按某种同步方式去读写数据,否则
    会造成数据错误,所以把其中一端关闭 close(fd))
    3) int pipefd[2]这里代表的是两个文件描述符,pipefd[0]--->读  read(pipefd[0], buf, len );
                                                                              pipefd[1]--->写  write(pipefd[1], buf, len);
    4) 使用结束后关闭对应的端口。


    特点:1、在数据交换前,管道两端都需要打开,如果你只打开了其中一端,此端就会被阻塞,直到另外一端也被打开。
               2、阻塞地读或者写:读的时候,如果没有数据可读,就会被阻塞。写的时候,没有空间,write就会被阻塞。
               3、非阻塞的方式读写:读的时候,如果没有数据,立刻返回,并且会设置对应的错误码;写的时候,如果没有

               空间,会立刻返回,并且会设置对应的错误码
   

例子:在两个进得到的间通讯,将父进程从键盘得到得内容通过子进程读取出来并显示

#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#include<string.h>
int main()
{
    char buf_w[128],buf_r[128]; 
    memset(buf_w,0,128);  //清空读区域内容
    memset(buf_r,0,128);  //清空写区域内容

    pid_t pid;
    int pipefd[2];

    if(pipe(pipefd) < 0) //管道创建失败
    {
        perror("creat pipe fail");
        exit(-1);
    }

    pid = fork();   //创建进程

    if(pid < 0) //进程创建失败
    {
        perror("fork error");
        exit(-1);
    }
    else if(pid == 0) //子进程
    {
        close(pipefd[1]); //关闭写
        read(pipefd[0],buf_r,128);//从管道中读
        printf(" 从父进程里读到的字符串是:  %s\n",buf_r);
        close(pipefd[0]);//关闭读
        exit(0);
    }
    else //父进程
    {
        close(pipefd[0]);//关闭读
        printf("please input string:\n");
        scanf("%s",buf_w);
        write(pipefd[1],buf_w,128);
        close(pipefd[1]);
        waitpid(pid,NULL,0);
        exit(0);
    }
    return 0;
}

结果:

猜你喜欢

转载自blog.csdn.net/qq_37589838/article/details/81183435