gpt4 book ai didi

C 从 fork 调用的多个 exec 中读取标准输出

转载 作者:行者123 更新时间:2023-12-02 17:53:03 24 4
gpt4 key购买 nike

在下面的代码中,一个进程创建一个子进程 (fork()),然后该子进程通过调用 exec() 来替换其自身。 exec 的 stdout 是写在 pipe 中的,而不是 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)
{
}
}

最佳答案

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

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

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

}
}


}

关于C 从 fork 调用的多个 exec 中读取标准输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12645236/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com