您好,我一直在开发一个程序,该程序会分叉孩子,稍后将从每个孩子中分叉出更多的孩子,但这不是我需要帮助的。当我运行我的程序时(在这里它是一个函数,但工作原理相同),我应该有一个父级(PPID)生成 3 个子级(PIDS = 1,2,3),但我得到的是相同的 PID 和 PPID 3次(我当前的代码)或在我得到3个父母,每个父母有一个孩子之前,PPID和PIDS都不同,但PPID与之前的孩子PID相同。在我最近的尝试中,它从未在孩子(儿子)上方显示父母(爸爸)消息。它应该看起来像这样
[dad] hi am I PID 1234 and I come from ####(dont care what this number is)
[son] hi i am PID 1111 and I come from PPID 1234
[son] hi i am PID 1112 and I come from PPID 1234
[son] hi i am PID 1113 and I come from PPID 1234
这是我的代码。我只是在可能的情况下寻找提示,除非这只是我犯的一个愚蠢的错误,例如“哦,只需将 fork() 移至子进程”或类似的错误。
我还有一个 child_count 这样我就可以轻松地计算孩子的数量。
int forking(null)
{
void about(char *);
int i=0;
int j=0;
int child_count =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");
printf("I am child #%d \n",child_count);
child_count++;
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 main( void )
{
printf( "[dad] pid %d\n", getpid() );
for ( int i = 0; i < 3; i++ )
if ( fork() == 0 )
{
printf( "[son] pid %d from pid %d\n", getpid(), getppid() );
exit( 0 );
}
for ( int i = 0; i < 3; i++ )
wait( NULL );
}
产生这个输出
[dad] pid 1777
[son] pid 1778 from pid 1777
[son] pid 1779 from pid 1777
[son] pid 1780 from pid 1777
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)