gpt4 book ai didi

c++ - 多个 fork() 带管道的 child

转载 作者:太空宇宙 更新时间:2023-11-04 12:15:26 30 4
gpt4 key购买 nike

我正在尝试用 C++ 编写一个程序,该程序使用 fork() 创建子项。它应该从 argv 中获取 child 的编号并创建这些 child ,每个 child 都在创建另一个 child 并通过管道相互通信....

Example ./a.exe 2

**OUTPUT**
P1 exists
P2 created
Write message: Hello
P1 sending message (“Hello”) to P2
P2 received message (“Hello”) from P1

我从 argv 中得到数字,创建正确数量的 child (我认为),读写管道的功能,一切都很好。但是我很难与多个 child 一起生活!!

  1. 我的第一个问题是,如果我在 argv 中放置超过 2 个,子顺序没有像它应该的那样上升!(稍后创建显示)
  2. 但我最大的问题是如果我写 一条包含 2 个单词的消息,我只能阅读空格前的第一个单词!我正在使用 scanf。

SOME OF MY CODE

//GETTING,CHECKING ARGV
//OPENING PIPE

         pid=fork();
if (pid!=0){


waitpid(pid,&child_status,0);
printf("\n\n****Parent Process:ALL CHILD FINISHED!****");

}
else if (pid==0)
{

printf("\n P%d Exists \n",i);
close (mypipe[READ_END]);
write(mypipe[WRITE_END], msg, 256); /* write pipe*/
close (mypipe[WRITE_END]);
printf("Write a message: \n");
scanf("%s",msg);
printf("\n P%d sending message: '%s' to P%d \n",i,msg,i+1);

do{
childpid[i] = fork();
if (childpid[i] > 0){


/* wait for child to terminate */
waitpid(childpid[i],&child_status,0);
}
else if (childpid[i] == 0)
{
/*child process childpid = 0*/
printf("\n P%d Created \n",i+1);
close (mypipe[WRITE_END]);
read(mypipe[READ_END], msg, 256); /* read pipe */
close (mypipe[READ_END]);
printf("\n P%d received message: '%s' from P%d \n",i+1,msg,i);
exit(0);
return;

}
else{
printf("Child Fork failed");
}
i++;
}

while (i<x);


}
else{
printf("Fork failed");
}
}

我读过其他类似的问题并尝试了很多东西但没有帮助!任何帮助将不胜感激!!谢谢!

最佳答案

您显示的代码中存在多个问题,并且评论中诊断出代码缺失。

一个问题是你关闭了第一个 child 中唯一的管道的两端,然后第二次关闭它(幸运的是你忽略了这个错误)。更严重的是,任何后续的 child 都只能使用封闭的管道,这对他们没有帮助。

另一个问题是父进程没有关闭管道;在这个程序中这可能无关紧要,因为您不会尝试读取到 EOF,但在大多数程序中,这很重要。

另一个问题是,在尝试将未初始化的消息写入管道之前,您不会从标准输入中读取消息。目前还不清楚是否应该将子级的标准输入连接到管道的读取端。即使消息不是那么长,您也将 256 个字节写入管道。

您会遇到多个单词的问题,因为 scanf("%s", msg) 旨在读取第一个空格(空格、换行符、制表符等)。在这种情况下,我可能会使用 fgets() 来读取信息。

我认为您需要为每个 child 准备一根新 pipe 。您可能应该对每个系统调用进行错误检查,但如果您有一个简单的错误报告功能,这会更容易,如下所示:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdarg.h>
#include <errno.h>

static char *arg0 = 0;

static void err_exit(const char *fmt, ...)
{
int errnum = errno;
va_list args;
va_start(args, fmt);
fprintf(stderr, "%s (%d): ", arg0, (int)getpid());
vfprintf(stderr, fmt, args);
va_end(args);
if (errnum != 0)
fprintf(stderr, "Error %d: %s\n", errnum, strerror(errnum));
exit(1);
}

int main(int argc, char **argv)
{
int i=1;
int x;
int pid, mypipe[2];
pid_t childpid[256];
int child_status;
char msg[256];

arg0 = argv[0];

if (argc != 2 || (x = atoi(argv[1])) <= 0)
err_exit("Usage: %s num-of-children\n", argv[0]);
if (pipe(mypipe) < 0)
err_exit("pipe error\n");

您认真考虑了如何组织事物以便将消息从一个进程中继到下一个进程。这只是一个开始...错误报告功能可能对您有些用处。

关于c++ - 多个 fork() 带管道的 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7924630/

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