c - 子进程如何从管道读取stdout,而父进程如何将stdin写入管道?

标签 c linux pipe

// This code is pasted from
// http://linux.die.net/man/2/pipe

#include <sys/wait.h>
#include <unistd.h>
int main(int argc, char *argv[])
{
    int pipefd[2];
    pid_t cpid;
    char buf;
    if (argc != 2) {
    fprintf(stderr, "Usage: %s <string>\n", argv[0]);
    exit(EXIT_FAILURE);
    }
    if (pipe(pipefd) == -1) {
        perror("pipe");
        exit(EXIT_FAILURE);
    }
    cpid = fork();
    if (cpid == -1) {
        perror("fork");
        exit(EXIT_FAILURE);
    }
    if (cpid == 0) {    /* Child reads from pipe */                   <----- Point A
        close(pipefd[1]);          /* Close unused write end */
        while (read(pipefd[0], &buf, 1) > 0)
            write(STDOUT_FILENO, &buf, 1);
        write(STDOUT_FILENO, "\n", 1);
        close(pipefd[0]);
        _exit(EXIT_SUCCESS);
    } else {            /* Parent writes argv[1] to pipe */           <----- Point B
        close(pipefd[0]);          /* Close unused read end */
        write(pipefd[1], argv[1], strlen(argv[1]));
        close(pipefd[1]);          /* Reader will see EOF */
        wait(NULL);                /* Wait for child */
        exit(EXIT_SUCCESS);
    }
}

据我了解,

if (...)
  ............;   ---+
else                 |---> " Only ONE of them can be reached! "
  ............;   ---+

那么,在此代码中,子进程如何从管道读取并且父进程如何写入管道?

最佳答案

fork() 的结果是一个进程变成两个进程(通过无性繁殖)。因此,虽然在一个进程中仍然会只采用 if/else block 的一个分支,但有两个进程,每个进程都会采用一条路径。

更具体地说,看看 fork() 返回的内容:父级的 PID,新子级的 0。除此之外,这两个过程几乎相同。因此,if (cpid == 0) 检查是 fork() 之后的常见模式,以便您可以在每个进程中执行不同的逻辑。就您而言,这是在一个进程中读取并在另一个进程中写入。

关于c - 子进程如何从管道读取stdout,而父进程如何将stdin写入管道?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434732/

相关文章:

linux - 如何将远程 Linux 服务器日志文件跟踪到本地 Windows 计算机

c - 分配内存和为数组分配内存的区别

c - 在 C 中,将文本文件读入结构数组,然后用该数组写入新的文本文件

linux - 将 grep 结果放入变量中

c - C Pipe 中的 Unix Shell 问题

c - 关于 C 中的 fork() 和 pipe() 等系统调用的问题

c - 为什么我的管道仅在我发送 SIGINT 时才结束

c - libpcap 从 AF_LINK sockaddr_dl (OSX) 获取 MAC

c - 我如何将结构的成员复制到 C 中的 double 组中?

linux - 用 gcc 汇编 32 位 x86 代码?