Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using fork() to make 3 children out of 1 parent in C (not C++)

Hi there I've been working on a program that forks children and later will fork more children from each child but that's not what I need help with. When I run my program (in here it is a function but works the same) I am supposed to have one parent(PPID) spawn 3 children (PIDS= 1,2,3) but what I get is either the same PID and PPID 3 times (my current code) or before I was getting 3 parents with each parent having one child and the PPIDS were different as well as the PIDS, but the PPIDs were just the same as the previous child PIDs. In my latest attempts it never displays the parent(dad) message above the child(son). It should look like this

[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

here is my code. I'm just looking for hints if possible unless it's just a silly mistake I've made like "oh just move the fork() to the child process" or something like that.

Also I have a child_count just so I can easily count the children.

 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;
}
like image 713
Jite Avatar asked Sep 29 '15 06:09

Jite


1 Answers

The parent needs to
- print a message
- call fork three times
- wait for the three children to exit

Each child needs to
- print a message
- exit

So the code is as simple as

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

which generates this output

[dad] pid 1777
[son] pid 1778 from pid 1777
[son] pid 1779 from pid 1777
[son] pid 1780 from pid 1777
like image 96
user3386109 Avatar answered Sep 22 '22 17:09

user3386109