Very basic problem with fork() using c

Hi guys,
I have the following code:

int main(int argc, char *argv[])  
{     
int pid1,pid2,i=0;
       pid1=fork();
      i+=2;
          if(!pid1) i++;
     if(i%3) pid2=fork();     
if (pid2==0)
     {
         printf("sea \n ");    
         i-=1;
     }
if(i>=2) printf("Mountain\n"); 

}

Please, can someone enlight me and explain WHY the output is

sea
mountain
mountain
sea ??

Why a 4 child is forked ? From where ?!
the if(i%3)

if the result is "ZERO", it should be read as FALSE by the program, right ? But even if the result is == 0 its like if the condition was true.

Can someone explain it to me?

You started with one process, then two processes that forked into 4 processes, three total fork calls. For the second fork, two were parents and two were children. Welcome to multiprocessing. Each process has its own copies of the variables. For instance if the first process was 1000, it forked off 1001 and then 1002, and 1001 forked off 1003. Actually, as I recall, the child tends to run before the parent of a fork, so 1001 might have forked 1002 before 1000 could, so it forks off 1003, but you can tell from the order of the printouts.

Ok, this part I got.

But how come ?
One process wasn't supposed to fork another process.

-P0 forks P1 and both have i=2

  • then only P1 does i++ because:
if(!pid1) i++

P1 is the forked child, who sees pid1==0 and P0 the father, who sees pid1>0

So, it means if(0) to P1 and if(true) to P0.
---

So far we have P0 with i=2 and P1 with i=3

-next step is:

if(i%3) pid2=fork();

For P1, the result of 3%3 will be 0,
so if ( 0 ) pid2 = fork();
and as far as I understood, P1 WONT FORK P2!!!

Instead, P0 will produce 2%3 == 2, so P0 will fork P2,

And we'll have only 3 processes.

Where is my mistake ?

---------- Post updated at 03:24 PM ---------- Previous update was at 03:19 PM ----------

Maybe because pid2 wasn't initialized ?
So when P0 tests pid2 and its value without being initialized is 0, P0 prints sea and mountain ?

I did not compile and test the code, but I don't think there are 4 processes. Fork is called twice, both times by the original process, creating two siblings.

I too suspect that the problem is the uninitialized pid2 in the first child; since it is an automatic variable, it may contain garbage. A printf statement will confirm.

Regards,
Alister

Yes, remember that you are working with 4 different variables, with values copied at fork. I think for security reasons the unitialized automatics are at least initially zeroes. Later, in subroutines, they might be your old stack frame values. Don't do that. Try putting pid's on the output and fflush( stdout ) to spit out full lines always, since the stdout is being shared.
LINUX Man Pages and LINUX Commands at the UNIX and Linux Forums
Man Page for getpid (all Section 3) - The UNIX and Linux Forums