使用fork()在C语言中用1个父项生成3个孩子(不是C++)

Jit*_*ite 5 c unix linux fork process

大家好,我一直在研究一个让孩子们分开的项目,然后将为每个孩子分叉更多的孩子,但这不是我需要帮助的.当我运行我的程序(在这里它是一个函数,但工作相同)我应该有一个父(PPID)产生3个孩子(PIDS = 1,2,3),但我得到的是相同的PID和PPID 3次(我当前的代码)或在我得到3个父母,每个父母有一个孩子和PPIDS与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
Run Code Online (Sandbox Code Playgroud)

这是我的代码.如果可能的话,我只是在寻找提示,除非这只是一个愚蠢的错误,我已经做了"哦,只是将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;
}
Run Code Online (Sandbox Code Playgroud)

use*_*109 5

父母需要
- 打印一条消息
- 三次调用
- 等待三个孩子退出

每个孩子都需要
- 打印一条消息
- 退出

所以代码就像

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 );
}
Run Code Online (Sandbox Code Playgroud)

生成此输出

[dad] pid 1777
[son] pid 1778 from pid 1777
[son] pid 1779 from pid 1777
[son] pid 1780 from pid 1777
Run Code Online (Sandbox Code Playgroud)