3

在下面的代码中,一个进程创建了一个子进程(fork()),然后该子进程通过调用exec()来替换自己。exec的标准输出是写在管道而不是 shell 中的。然后父进程从管道中读取 exec 使用 while (read(pipefd[0], buffer, sizeof(buffer)) != 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)
    {
    }
}
4

3 回答 3

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);

        }
    }


}
于 2012-09-28T20:24:27.703 回答
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)
{
}

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

于 2012-09-28T18:55:24.147 回答
0

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

于 2012-09-28T19:11:54.767 回答