#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.


#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.