simple fork question

When executing this simple program:

#include <unistd.h>
void main()
{
int f;
printf("\n Parent procces ID=%d\n",getpid());
f=fork();
if(f==0)
{
printf("\n Child process ID=%d father=%d\n",getpid(),getppid());
}
exit(0);
}

I get this result:

#BadCommand in ~>flag2
#
# Parent procces ID=8297
#
# Child process ID=8298 father=1
#BadCommand in ~>

So, my question is: Why is father=1 when it should be 8297 ???

If I insert the command
sleep(2)
just before exit(0) then the 'father' is displayed correctly.
Why is that? Can anyone help me out?

When a process exits, a lot of stuff happens. One thing is that the kernel scans the process table to see if the exiting process has any children. If so, those children get a new parent. The new parent is always init which has a pid of 1.

The ppid is the current parent, not the, um, biological parent.

If you want reliably get the pid of the process that actually issued the fork, record it before the fork. But it isn't useful for anything, except maybe logging.

try running this code...

#include <unistd.h>
void main()
{
int f;
printf("\n Parent procces ID=%d\n",getpid());
f=fork();
if(f==0)
{
printf("\n Child process ID=%d father=%d\n",getpid(),getppid());
}
else
{
wait(0);
}
exit(0);
}

Here's the output:

./a.out

Parent procces ID=27711

Child process ID=27712 father=27711

The problem in the previous code is that the parent does not wait for the termination of the child process....Hence sometimes the parent process dies before the child ..Hence the init process(pid=1) becomes the parent of the child process...

By adding wait() or waitpid() we ensure that the parent waits for the termination of the child...

Pls. correct me if I am wrong....!!!