代码如下:

#include "all.h"

int main()
{
    int fd[2];

    if (pipe(fd) < 0)
        errsys("pipe error");
    if (fork() == 0) {
        close(1);
        dup(fd[1]);
        close(fd[1]);
        close(fd[0]);
        if (execlp("ls", "ls", NULL) < 0)
            errsys("execlp ls error");
        exit(1);
    }
    if (fork() == 0) {
        close(0);
        dup(fd[0]);
        close(fd[0]);
        close(fd[1]);
        if (execl("putfile", "putfile", NULL) < 0)
            errsys("execl putfile error");
        exit(1);
    }
    close(fd[0]);
    close(fd[1]);
    wait(NULL);
    wait(NULL);

    return 0;
}

putfile程序从标准输入读,并全部写到 a.txt 文件中,代码如下:

#include "all.h"

#define MAXBUF 10

int main()
{
    int fd, n;
    char buf[MAXBUF];

    fd = open("a.txt", O_TRUNC, O_CREAT | O_WRONLY, 0664);
    if (fd < 0)
        errsys("open error");
    while ((n = read(STDIN_FILENO, buf, MAXBUF)) == MAXBUF)
        write(fd, buf, n);
    if (n < 0)
        errsys("read error");
    else
        write(fd, buf, n);

    return 0;
}

Linux shell 对管道就是这样处理的。