进程间通信--pipe

管道

管道又名匿名管道,这是一种最基本的IPC机制,由pipe函数创建:

#include <unistd.h>
int pipe(int pipefd[2]);

返回值:成功返回0,失败返回-1;

pipe[1]指向pipe的写端

pipe[0]指向pipe的读端

使用pipe[1]向管道写数据,pipe[0]向管道读数据,使用pipe读写,其实是在读写内核缓冲区。

pipe管道一般用于父子类的关系进程之间,pipe管道是阻塞的

pipe管道可以用read和write进行读写

举例:

#include <iostream>                                                                                                                                                                        
#include <unistd.h>
#include <string.h>

int main()
{
    int fd[2] = {0};
    int ret = pipe(fd);
    if(ret == -1){
        printf("create pipe err!\n");
        return 0;
    }
    pid_t pid = fork();
    if(pid < 0)
    {
        printf("fork pid err!\n");
        return 0;
    }
    else if(pid > 0)
    {
        char buf[1024] = {0};
        int num = 10;
        sprintf(buf,"hello child,I'm father:%d\n",pid);
        while(num--){
            write(fd[1],buf,strlen(buf)+1);
        }
        close(fd[1]);
        sleep(1000);
    }
    else
    {
        char buf[1024] = {0};
        int num = 10;
        while(num --)
        {
            int n = read(fd[0],buf,1024);
            printf("recv[%d]:%s",n,buf);
        }
        close(fd[0]);
    }
}

  

猜你喜欢

转载自www.cnblogs.com/flycc/p/12814911.html