C从fork调用的多个exec读取stdout

时间:2012-09-28 18:14:01

标签: c exec fork pipe

在下面的代码中,进程创建一个子进程( fork()),然后子进程通过调用 exec()来替换自己。 exec的 stdout 写在管道而不是shell中。然后父进程从管道中读取exec用 while写的内容(读取(pipefd [0],缓冲区,sizeof(缓冲区))!= 0)

有人可以告诉我如何做与上述完全相同的事情,但是有N个子进程(他们用exec替换自己如上)。

int pipefd[2];
pipe(pipefd);

if (fork() == 0)
{
    close(pipefd[0]);    // close reading end in the child

    dup2(pipefd[1], 1);  // send stdout to the pipe
    dup2(pipefd[1], 2);  // send stderr to the pipe

    close(pipefd[1]);    // this descriptor is no longer needed

    exec(...);
}
else
{
    // parent

    char buffer[1024];

    close(pipefd[1]);  // close the write end of the pipe in the parent

    while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
    {
    }
}

3 个答案:

答案 0 :(得分:1)

我找到了答案。我创建了一个管道数组,以便进程不会覆盖另一个进程的输出。

这是我的代码。你发现有什么错吗?

#include <signal.h>
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include <sys/time.h>

#define N 10

int main(int argc, char *argv[]) {
    ssize_t readlen;
    int pipefd[N][2];
    int i;
    for (i = 0; i < N; i++) {
        pipe(pipefd[i]);
    }

    int pid = getpid();

    for (i = 0; i < N; i++) {
        if (fork() == 0) //The parent process will keep looping
        {

            close(pipefd[i][0]);    // close reading end in the child

            dup2(pipefd[i][1], 1);  // send stdout to the pipe
            dup2(pipefd[i][1], 2);  // send stderr to the pipe

            close(pipefd[i][1]);    // this descriptor is no longer needed

            char b[50];
            sprintf( b, "%d", i);

            execl("/bin/echo", "echo", b,NULL);


        }
    }

    if (pid == getpid()) {

        // parent

        char buffer[1024];

        for (i = 0; i < N; i++) {
            close(pipefd[i][1]);  // close the write end of the pipe in the parent

            while ((readlen=read(pipefd[i][0], buffer, sizeof(buffer))) != 0)
            {
                        buffer[readlen] = '\0';
            }

            printf("%s\n",buffer);

        }
    }


}

答案 1 :(得分:0)

也许这段代码可以完成这项工作:

const int N = 10; //Number of child processes
int pipefd[2];
pipe(pipefd);
int i;
for (i = 0; i < N; i++) {
    if (fork() == 0) //The parent process will keep looping
    {
        close(pipefd[0]);    // close reading end in the child

        dup2(pipefd[1], 1);  // send stdout to the pipe
        dup2(pipefd[1], 2);  // send stderr to the pipe

        close(pipefd[1]);    // this descriptor is no longer needed

        exec(...);
    }
}

// parent

char buffer[1024];

close(pipefd[1]);  // close the write end of the pipe in the parent

while (read(pipefd[0], buffer, sizeof(buffer)) != 0)
{
}

警告:输出将混合。如果您希望所有进程在不混合的情况下转储数据,那么您应该设法同步进程(例如,通过公共锁)。

答案 2 :(得分:0)

我认为您可以在文件系统的任何位置(如本地套接字)创建命名的chanel,并将所有接收的数据读取到父进程。因此,子进程必须将其获取的数据写入此通道。它将是类似unix的架构。