命名管道-运行子进程

时间:2019-09-10 10:05:31

标签: c

我试图在C中使用命名管道在非阻塞模式下从路径中的后台运行子进程,并读取子进程的输出。

这是我的代码:

int fifo_in = open("fifo_1", O_RDONLY| O_NONBLOCK);
 int fifo_out = open("fifo_2", O_WRONLY| O_NONBLOCK);
 dup2(fifo_in, 0);
 dup2(fifo_out, 1);

 char app[] = "/usr/local/bin/probemB";
 char * const argsv[] = { app, "1", NULL };
 if (execv(app, argsv) < 0) {
            printf("execv error\n");

            exit(4);
 }

稍后我将使用读取功能读取子进程的输出。

但是问题是execv在从进程读取输出时阻塞,而不是让我读取。

有人可以帮我解决上述问题吗?

1 个答案:

答案 0 :(得分:2)

您错了,execv被阻止了。

如果execv有效,它将永远不会返回。它替换您的程序。您需要为fork execv进行新的处理:

<div class="row">
  <div style="left: 0%; height: 10px; background: red;">

  </div>
  <div style="left: 30%; height: 10px; background: green;">

  </div>
  <div style="left: 50%; height: 10px; background: blue;">

  </div>
  <div style="left: 70%; height: 10px; background: orange;">

  </div>
</div>

另一件事,您似乎有两个不同且未连接的命名管道。您应该只打开一个管道,以便在父进程中进行读取以及在子进程中进行写入:

if (fork() == 0)
{
    // In child process, first setup the file descriptors
    dup2(fifo_out, STDOUT_FILENO);  // Writes to standard output will be written to the pipe
    close(fifo_out);  // These are not needed anymore
    close(fifo_in);

    // Run the program with execv...
}
else
{
    // Unless there was an error, this is in the parent process
    close(fifo_out);

    // TODO: Read from fifo_in, which will contain the standard output of the child process
}

但是,如果您只想内部通信,则不需要命名管道。而是使用pipe函数创建的匿名管道。