Ishaaq K Chandy wrote:
> Hi all,
>
> I've been experimenting with UNIX C programming. I made a program
> recently. All this (useless) program does is to print out the PID of
> the process using getpid(), fork a child process, get the child to
> print its PID and to print out its parent's PID using getppid() and
> then exit.
>
> The problem is that the parent's getpid() output and the child's
> getppid() output do not match! getppid() always returns the number
> '1'. Why is this happening?
>
> I did the same on an AIX machine, and it worked as I expected it to.
>
> Thanks in advance,
> Ishaaq
1 is the pid of init. If you did something as follows:
printf("Parent pid is %i\n",getpid());
if( (childpid=fork()) ==0 )
{
printf("Child pid is %i, parent pid is %i\n",getpid(),getppid());
exit(0);
}
exit(0);
you may get the parent pid as 1. It depends on which process executes
just after fork - if child executes, it gets the pid of parent and
terminates. But if parent executes first, it terminates before the child
is executed, so the child's parent becomes init-which has pid 1. Then
the child terminates and becomes a zombie.