In: Computer Science
The following program calls the fork() system call to create a child process.
Suppose that the actual pids of the parent process and child process are as follows:
Parent process: 801
Child process: 802 (as returned by fork)
Assume all supporting libraries have been included.
=> Use the answer text field to write the values of the pids printed at lines 1, 2, 3, and 4 (indicate each line number and the value printed).
int main()
{
pid_t pid, pid1;
pid = fork(); /* fork a child process */
if (pid < 0) {
fprintf(stderr, "Error creating child.\n");
exit(-1);
}
else if (pid > 0) {
wait(NULL); /* move off the ready queue */
pid1 = getpid();
printf(pid); /* Line 1 */
printf(pid1); /* Line 2 */
}
else {
pid1 = getpid();
printf(pid); /* Line 3 */
printf(pid1); /* Line 4 */
}
return 0;
}
Please find the below explanations.
Please provide your feedback
Thanks and Happy Learning!
A 'pid_t pid = fork()' call can have 2 scenarios
1. On success, the PID of the child process is returned to the parent, and 0 is returned in the child.
That means on a successful fork() call the value in the 'pid' variable will be the PID of the child process.
2. On failure, -1 is returned in the parent, and no child process is created
That means
If the PID value is zero(0), then that indicates a child process
If the PID value is greater than zero(0), then that indicates a parent process
If the PID value is equal to zero(0), then that indicates creation of child process failed.
Also the getpid() function will return the PID of the process which is invoking that call. That means if the getpid() is invoked by the parent then the call returns the parents PID, and if it is invoked by the child then the call returns childs PID.
With the above points in mind, please see the valus of PID's printed in each line below
Line 1 : PID = 802 (Child PID)
Line 2 : PID = 801 (Parent PID, because parent process invoked getpid())
Line 3: PID = 802 (Child PID)
Line 4: PID = 802 (Child PID, because child process invoked getpid())