p11-5.c

来自「SUN Solaris8平台下进程间通信」· C语言 代码 · 共 31 行

C
31
字号
#include <stdio.h>#include <unistd.h>#include <fcntl.h>#include "err_exit.h"main(int argc, char *argv){    int pid, fd[2],len;    char buffer[PIPE_BUF];    FILE *stream;     if ( pipe(fd) != 0)         err_exit("pipe creation problem");    if ( (pid = fork()) == -1)        err_exit("fork failed");     if (pid == 0) {   /* 子进程 */        close(fd[1]);                /* 不使用管道的写端 */        dup2(fd[0],0);               /* 关闭stdin,重定向管道的输入端至stdin */        close(fd[0]);         /* 用cat过滤程序的输出 */        if (execl("/bin/cat","cat","-n", NULL) == -1)            err_exit("Unable to run cat");     }    else {            /* 父进程 */        close(fd[0]);                /* 不使用管道的输入端 */        printf("you can input any text below:\n");        dup2(fd[1],1);                 /* 关闭stdout,重定向管道的输出端至stdout */        close(fd[1]);        while (gets(buffer) != NULL)           puts(buffer);             /* 写至管道*/    } } 

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?