Linux进程间通信之管道(pipe)的学习和示例

管道(pipe)可用于具有亲缘关系进程间的通信,历史上它们是半双工的。对于管道两端的进程而言,管道就是一个文件,但它不是普通的文件,它不属于某种文件系统,而是自立门户,单独构成一种文件系统,并且只存在与内存中。一个进程向管道中写的内容被管道另一端的进程读出。写入的内容每次都添加在管道缓冲区的末尾,并且每次都是从缓冲区的头部读出数据。

一、管道pipe()函数介绍

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

pipe() creates a pipe, a unidirectional data channel that can be used for interprocess communication. The array pipefd is used to return two file descriptors referring to the ends of the pipe. pipefd[0] refers to the read end of the pipe. pipefd[1] refers to the write end of the pipe. Data written to the write end of the pipe is buffered by the kernel until it
is read from the read end of the pipe.

二、管道pipe实例

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

#define MAXLINE 1024

int main(void)
{
        int nbytes;
        int pipefd[2];
        // pipefd[0]-read, pipefd[1]-write
        pid_t pid;
        char line[MAXLINE];
        const char *str = "Pipe Demo - Xie Yincai's Blog\n";

        if(pipe(pipefd) < 0) {
                // 创建管道出错
                printf("pipe error\n");
                return 1;
        }

        if((pid = fork()) < 0) {
                // 创建子进程出错
                printf("fork error\n");
                return 1;
        }
        else if(pid > 0) {
                // 父进程
                close(pipefd[0]); // 关闭读
                write(pipefd[1], str, strlen(str));
        }
        else {
                // 子进程
                close(pipefd[1]); // 关闭写
                nbytes = read(pipefd[0], line, MAXLINE);
                write(STDOUT_FILENO, line, nbytes);
        }

        return 0;
}

三、运行结果

[ycxie@fedora Workspace]$ gcc testpipe.c -o testpipe -Wall
[ycxie@fedora Workspace]$ ./testpipe
Pipe Demo - Xie Yincai's Blog

Leave a Reply

Your email address will not be published. Required fields are marked *