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;
}
Here is the solution. Please do upvote thank you.
Output:
Line 1: 802
Line 2: 801
Line 3: 0
Line 4: 802
Explanation:
Parent Process Id = 801 (Given)
Child Process Id = 802 (Given)
Flow of the program and initialisation of all pid variables:
The "else if block" (for pid > 0) executes for the parent
process, it stays on hold until child process terminates because of
invocation of wait system call.
The control moves to the child process i.e. the "else block" (i.e.
pid == 0) in it and calls getpid() which makes pid1 = Child Process
id = 802.
After that, the wait ends and the parent process resumes i.e. its
"else if block" again. It has its variable pid = 802 (the process
id of the child process returned from fork()) and pid1 = 801 (i.e.
process id of the parent process' itself got from calling getpid()
function).
Get Answers For Free
Most questions answered within 1 hours.