Unix C管道问题

RoR*_*RoR 4 c unix pipe

我试图了解管道的用法.

父进程将进行管道传输,如果是父进程,子进程将继承管道.那么现在我们与子进程有直接联系,他们可以沟通吗?

当我们开始关闭管道并重定向管道时,我迷路了.有没有人对关闭管道和重定向管道有一个很好的解释?

先感谢您.

Zif*_*ion 6

这是交易.

  1. 管道是一种软件抽象,它有两个端点,每个端点都是一个fd.无论你在一端写什么(写fd),你都可以读到另一端(读fd).
  2. 使用管道的技巧是使用管道的读取fd切换某个进程的stdin.现在,你可以写入管道的写入fd,当另一个进程读取他认为是他的stdin时,他实际上读取了管道的读取fd(并获取了你的数据).
  3. 对于双向通信,您可以获取另一个管道,并使用管道的写入fd切换进程的标准输出.现在,无论进程写入其stdout,您都可以读取管道的读取fd.

这是它的样子:

P1=[WR FD]===========[RD FD]=[STDIN]=P2
P1=[RD FD]===========[WR FD]=[STDOUT]=P2

P1 and P2 are processes. And "===" depict the pipes.
Run Code Online (Sandbox Code Playgroud)

您的问题专门针对关闭和重定向.当你执行我之前提到的开关时,它就会发挥作用.假设您已通过使用pipe()系统调用获取了管道.

int fd[2];
pipe(fd);
Run Code Online (Sandbox Code Playgroud)

现在您创建一个子进程,并在该进程中执行切换,如下所示:

if (!fork()) // 0 return value indicates that you are in the child process
{
    dup2(fd[0], 0); // dup2 first closes 0 in the child process, then duplicates
                    // fd[0] as 0; keep in mind that 0 is stdin and fd[0] is the
                    // read end of the pipe

    exec(something); // start the new process, which when it reads stdin, will be
                     // reading the pipe instead
}
Run Code Online (Sandbox Code Playgroud)