您好我有一个关于使用fork()创建更多子级的问题,该问题基于我之前提出的问题using fork() to make 3 children out of 1 parent in C (not C++)
我希望我的输出看起来像这样(#s是简单的,只是用来说明顺序)
[grandpa]hi am I PID 1234 and I come from ####(dont care what this number is)
[dad] hi i am PID 2111 and I come from PPID 1234
[son] hi i am PID 3111 and I come from PPID 2111
[son] hi i am PID 3112 and I come from PPID 2111
[son] hi i am PID 3113 and I come from PPID 2111
[dad] hi i am PID 2112 and I come from PPID 1234
[son] hi i am PID 3111 and I come from PPID 2112
[son] hi i am PID 3112 and I come from PPID 2112
[son] hi i am PID 3113 and I come from PPID 2112
[dad] hi i am PID 2113 and I come from PPID 1234
[son] hi i am PID 3111 and I come from PPID 2113
[son] hi i am PID 3112 and I come from PPID 2113
[son] hi i am PID 3113 and I come from PPID 2113
但我的输出如下:
关于爸爸ppid,最后似乎没问题,除了最后一个,并且大多数PID似乎无序。我不知道为什么有一个儿子,然后是5个儿子,然后是3个儿子。这是我的代码:
int grandforking(null)
{
Gen1 (null);
return 0;
}
int Gen1 (null)
{
void about(char *);
int i=0;
int j=0;
about("grandpa");
for(i = 0; i < 3; i++ )
{
pid_t child = 0;
child = fork();
if (child < 0)
{ //unable to fork error
perror ("Unable to fork");
exit(-1);
}
else if (child == 0)
{ //child process
Gen2 (null);
exit(0);
}
else
{ //parent process
//(do nothing)
}
}
for(j = 0; j < 3; j++ )
{
wait(NULL);//wait for parent to acknowledge child process
}
return 0;
}
int Gen2 (null)
{
int i=0;
int j=0;
about("dad");
for(i = 0; i < 3; i++ )
{
pid_t child = 0;
child = fork();
if (child < 0)
{ //unable to fork error
perror ("Unable to fork");
exit(-1);
}
else if (child == 0)
{ //child process
about ("son");
exit(0);
}
else
{ //parent process
//(do nothing)
}
}
for(j = 0; j < 3; j++ )
{
wait(NULL);//wait for parent to acknowledge child process
}
return 0;
}
答案 0 :(得分:2)
启动进程后,调度程序可以按照自己的意愿运行它们。如果您有多个处理器,这包括同时运行多个。 (像所有人一样,这些天。)
它当然可以启动一个孩子,运行该孩子一段时间,然后再回到父母打印消息。
如果你在父母产生孩子之前拥有识别的printf,你的订购会稍微好一些。
但是你获得锁步顺序的唯一方法就是你做了类似的事情: