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.

Recommended Answers

All 4 Replies

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.

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

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.

ok. the problem was in my header files.
thanks.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.