Start by reading the fork man page as well as the getppid / getpid man pages.
From fork's
On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.
So this should be something down the lines of
if ((pid=fork())==0){
printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
printf("Dont yada yada me, im your parent with pid %u ", getpid());
}
As to your question:
This is the child process. My pid is 22163 and my parent's id is 0.
This is the child process. My pid is 22162 and my parent's id is 22163.
fork()
executes before the printf
. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork()
will return 0
to the child process, and the pid
of the child process to the parent process.
You get two running processes, each one will execute this instruction statement:
printf ("... My pid is %d and my parent's id is %d",getpid(),0);
and
printf ("... My pid is %d and my parent's id is %d",getpid(),22163);
~
To wrap it up, the above line is the child, specifying its pid
. The second line is the parent process, specifying its id (22162) and its child's (22163).