This is the C code to test fork() system call:
#include<stdio.h>
#include<stdlib.h>
#include<sys/types.h>
#include<unistd.h>
#include<wait.h>
int main(int argc, char *argv[])
{
printf("I am: %d\n", (int)getpid());
pid_t pid = fork();
printf("fork returned: %d\n", (int)pid);
if (pid < 0)
{
perror("fork failed");
}
if (pid==0)
{
printf("I am the child with pid %d\n", (int)getpid());
sleep(5);
printf("Child exiting...\n");
exit(0);
}
printf("I am the parent with pid %d, waiting for the child\n", (int)getpid());
wait(NULL);
printf("Parent ending. \n");
return 0;
}
The output in terminal is:
I am: 25110
fork returned: 25111
I am the parent with pid 25110, waiting for the child
fork returned: 0
I am the child with pid 25111
Child exiting...
Parent ending.
Question: When fork returned: 0, it is in the child process. But the child process shows I am the child with pid 25111. I thought the child process pid should be 0, why it changes to 25111?
Same thing with the parent process, fork returned 25111, but getpid() returns 25110 (I am the parent with pid 25110, waiting for the child)
forkis tricky to understand, so take time! Read also many times fork(2) and fork wikipage - Basile Starynkevitchinit- Claudio Corteseinitis pid 1. There is literally (this is a POSIX requirement) no such thing as pid 0 since 0 has special meaning to various interfaces that take or return pids -- in particular,fork. - R.. GitHub STOP HELPING ICEpsshows a pid 0 called "swapper". (But, yes, init is pid 1.) - Steve Summit