0

hello
i am trying to figure out the output of this specific code

int main()
{
    int i , parent_id , ans ;

    parent_id = getpid() ; 
   
    for ( i = 1 ; i <= 5 ; i++ )
    {

       if ( getpid() == parent_id )
       {

         ans = fork() ;
 
         wait() ;
       }

       if ( ans == 0 )
       {
  
         sleep(i) ;
  
         printf ( " \n I am a child my pid is %d " , getpid() ) ;

         exit(0) ;
       } 
     }

     printf ( " \n I am the father my pid is %d " , parent_id ) ;
   
     return 0 ;
}

the output is very strange. it prints the first child first , the father second and then all the other children.
i thought exit(0) suppose to kill the child.
i thought the program will print all the children first and then the father
but it doing something different that i dont understand.

2
Contributors
4
Replies
6
Views
8 Years
Discussion Span
Last Post by emilio
0

That, as soon as you call fork(), you have no control over the scheduling of the parent and child processes.
Anything can happen in any order, and can vary from one run to another.

0

but as soon as i called fork i called wait()
that means that the father must wait for his son.
correct me if i wrong

0

wait apparently takes a parameter, which yours does not.

Also, since your wait immediate follows the fork call, it means BOTH the parent and child will be doing some waiting.

I've no idea what you're running, or what results you're getting.

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.