进程间通讯之匿名管道阐述

前言

每一个进程各自有不一样的用户地址空间,任何一个进程的全局变量在另外一个进程中都看不到,因此进程之间要交换数据必须经过内核,在内核中开辟一块缓冲区,进程1把数据从用户空间拷到内核缓冲区,进程2再从内核缓冲区把数据读走,内核提供的这种机制称为进程间通讯(IPC,InterProcess Communication)。以下图所示。
图片描述linux

管道

什么是管道

若是用过Linux命令,那么咱们对这个名词不会陌生,咱们常常经过“|”来使用管道,好比ls -l|grep string.
管道是一个进程链接数据流到另外一个进程的通道,一般一个进程的输出经过管道链接到另外一个进程的输入。shell

高层管道

语法

#include <stdio.h>
FILE* popen (const char *command, const char *open_mode);
int pclose(FILE *stream_to_close);

用法

popen会启动另外一个新进程,而后传递数据给它或从它接收数据。
command是要运行的程序名和相应的参数, open_mode只能是"r"或"w"
popen返回一个FILE类型指针, 而后就可使用I/O文件函数对其操做。
当open_mode为“r”时, 表示主程序能够从被调用程序读取数据
当open_mode为“w”时, 表示主程序能够写数据到被调用程序
pclose用于关闭由popen建立出的关联文件流。pclose只在popen启动的进程结束后才返回,若是调用pclose时被调用进程仍在运行,pclose会等其结束。它返回关闭的文件流所在进程的退出码。编程

示例

代码

//
// Created by         : Harris Zhu
// Filename           : test.c
// Author             : Harris Zhu
// Created On         : 2017-08-20 01:18
// Last Modified      :
// Update Count       : 2017-08-20 01:18
// Tags               :
// Description        :
// Conclusion         :
//
//=======================================================================

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

#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)

int main(int argc, char** argv)
{
    FILE *rdFP = NULL;
    FILE *writeFP = NULL;
    char buf[BUFSIZ + 1];
    int num_of_chars = 0;

    memset(buf, '\0', sizeof(buf));

    //打开ls做为读接口
    rdFP = popen("ls -l", "r");
    if(!rdFP)
    {
        ERR_EXIT("failed to open read pipe");
    }
    //打开grep做为写接口
  wrFP = popen("grep \\\\-rw-rw-r--", "w");
    if(!wrFP)
    {
        ERR_EXIT("failed to open write pipe");
    }
    if(rdFP && wrFP)
    {
        //从ls读取BUFSIZ字符
        num_of_chars = fread(buf, sizeof(char), BUFSIZ, rdFP);
        while(num_of_chars > 0)
        {
            buf[num_of_chars] = '\0';
            //把数据写入grep
            fwrite(buf, sizeof(char), num_of_chars, wrFP);
            //循环读取数据直到读完全部数据
            num_of_chars = fread(buf, sizeof(char), BUFSIZ, rdFP);
        }
        //关闭文件流
        pclose(rdFP);
        pclose(wrFP);
    }
    exit(EXIT_SUCCESS);
}

输出

-rw-rw-r--. 1 harriszh harriszh   126 Aug 20 01:28 makefile
-rw-rw-r--. 1 harriszh harriszh  1560 Aug 20 01:32 test.c

由于grep缘由,在例子中须要使用4个 来escape -, 不然grep 被把它当成选项
另外一种写法是函数

wrFP = popen("grep \'\\-rw-rw-r--\'", "w");

优缺点

当popen运行一个程序时,它先启动shell, 而后当command字符串做为参数传递给它。
优势是参数扩展是由shell完成,因此可使用各类通配符
缺点是每次打开一个程序,还要启动一个shell, 也就是说一次popen调用,启动了两个进程,从效率和资源看,popen都不太理想。spa

底层管道

popen是高级函数,pipe则是底层调用,它不须要启动shell来解释命令,并且它能提供更多对数据的控制.net

语法

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

用法

调用pipe函数时在内核中开辟一块缓冲区(称为管道)用于通讯,它有一个读端一个写端,而后经过filedes参数传出给用户程序两个文件描述符,filedes[0]指向管道的读端,filedes[1]指向管道的写端(很好记,就像0是标准输入1是标准输出同样)。因此管道在用户程序看起来就像一个打开的文件,经过read(filedes[0]);或者write(filedes[1]);向这个文件读写数据实际上是在读写内核缓冲区。pipe函数调用成功返回0,调用失败返回-1。3d

通讯机制

图片描述

示例

代码

//
// Created by         : Harris Zhu
// Filename           : test.c
// Author             : Harris Zhu
// Created On         : 2017-08-19 13:28
// Last Modified      :
// Update Count       : 2017-08-19 13:28
// Tags               :
// Description        :
// Conclusion         :
//
//=======================================================================

#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
#include <string.h>
#include <time.h>

#define ERR_EXIT(m) \
    do { \
        perror(m); \
        exit(EXIT_FAILURE); \
    } while(0)


int main(int argc, char** argv)
{
    int pipefd[2];
    if (pipe(pipefd) == -1)
    {
        ERR_EXIT("open pipe error");
    }
    pid_t pid;
    pid = fork();
#ifdef SWITCH
    char r_buf[100]={0};
    char w_buf[100]="hello\0";
    switch(pid)
    {
    case -1:
        ERR_EXIT("fork error");
        break;
    case 0:
        close(pipefd[0]);
        printf("son: sending %s, size = %d\n", w_buf, sizeof(w_buf));
        write(pipefd[1], w_buf, sizeof(w_buf));
        close(pipefd[1]);
        exit(EXIT_SUCCESS);
        break;
    default:
        close(pipefd[1]);
        read(pipefd[0], r_buf, 100);
        printf("paraent: receive %s, size=%d\n", r_buf, sizeof(r_buf));
        close(pipefd[0]);
//        exit(EXIT_SUCCESS);
        break;
    }
#else
    if(pid < 0)
    {
        ERR_EXIT("fork error");
    } else {
        if(pid == 0)
        {
            close(pipefd[0]);
            char *w_buf="hello";
            printf("son: sending %s, size = %d\n", w_buf, strlen(w_buf));
            write(pipefd[1], "hello", 5);
            close(pipefd[1]);
            exit(EXIT_SUCCESS);
        } else {
            char r_buf[100]={0};
            close(pipefd[1]);
            read(pipefd[0], r_buf, 5);
            printf("paraent: receive %s, size=%d\n", r_buf, strlen(r_buf));
            close(pipefd[0]);
            exit(EXIT_SUCCESS);
        }
    }
#endif
    return 0;
}

解释

  1. 父进程调用pipe开辟管道,获得两个文件描述符指向管道的两端。指针

  2. 父进程调用fork建立子进程,那么子进程也有两个文件描述符指向同一管道。code

  3. 父进程关闭管道写端,子进程关闭管道读端。子进程能够往管道里写,父进程能够从管道里读,管道是用环形队列实现的,数据从写端流入从读端流出,这样就实现了进程间通讯。blog

注意点

两个进程经过一个管道只能实现单向通讯,好比最上面的例子,父进程读子进程写,若是有时候也须要子进程读父进程写,就必须另开一个管道。
管道的读写端经过打开的文件描述符来传递,所以要通讯的两个进程必须从它们的公共祖先那里继承管道文件描述符。上面的例子是父进程把文件描述符传给子进程以后父子进程之间通讯,也能够父进程fork两次,把文件描述符传给两个子进程,而后两个子进程之间通讯,总之须要经过fork传递文件描述符使两个进程都能访问同一管道,它们才能通讯。
通讯进程须要是父子进程关系,这使得它的应用受到了很大限制,这时咱们能够用命名管道来解决

后言

pipe的使用和原理很是简单,因此本文不过多解释展开,若有问题讲写邮件本人

参考:
linux系统编程之管道

相关文章
相关标签/搜索