Interview Question
Country: United States
Try this out:
pid_t pid;
for(i=0; i<20; i++) {
if( ( pid_t = fork()) !=0 ) { //staying in parent space
printf("Fork num. %d returned value: %ld\n", (long)pid);
printf("After above fork, parent pid %ld\n, (long)getpid());
}
}
Parent process PID will always remain same irrespective of number of forks. Adding some working code for benefit of all.
#include<stdio.h>
#include<unistd.h>
main()
{
pid_t parent = getpid();
int i;
for (i = 1; i <= 5; i++)
{
pid_t forkpid;
pid_t curprocess = getpid();
if (curprocess == parent) // Make sure we don't get into infinite loop
{
forkpid = fork();
curprocess = getpid(); // override value for child
}
if (parent == curprocess)
printf("Fork number: %d, parent process id %ld\n", i, (long)curprocess);
else
printf("Iteration number: %d, child process id %ld\n", i, (long)curprocess);
}
}
when a process calls fork to create a child, fork returns the pid of child
- bigphatkdawg September 19, 2013it does not change the pid of the process
getpid will still show it's original pid
if a process called fork 100 times, each time fork will return a different pid (of the children) but getpid in the parent process is always the same