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.
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.
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