I have the following function:
void test_fork()
{
pid_t id;
printf("Parent process id: %d\n", getpid());
id = fork();
if (id == 0)
printf("\nChild:");
else if (id > 0)
printf("\nParent:");
else
exit(EXIT_FAILURE);
printf("\nprocess id: %d\n", getpid());
printf("parent process id: %d\n", getppid());
}
My doubt is related to its output, in particular sometimes I have for example the following and straightforward output:
Parent process id: 879
Parent:
process id: 879
parent process id: 878
Child:
process id: 881
parent process id: 879
Where the last id is equal to its parent id (as would be expected).
But sometimes the output is for example:
Parent process id: 858
Parent:
process id: 858
parent process id: 857
Child:
process id: 860
parent process id: 1
Where the last id is not equal to its parent process id, but it's equal to 1 (that should be the id of the init process).
How can it be possible?
It is because the parent process has already finished when the child asks for its parent's pid, so the child's parent defaults to the init
process. init process has a pid
of 1
.
Try putting a wait()
in the parent process !!