Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Question # 1: Understand the below program carefully and explain each line accor

ID: 3621215 • Letter: Q

Question

Question # 1:
Understand the below program carefully and explain each line accordingly.
#include <stdio.h>
void main ( )
1………………… {
2……………………….int pid, status;
3……………………….pid = fork ( );
4……………………….if (pid = = -1)
5……………………… {
6……………………………printf(“fork failed ”);
7……………………………exit(1) ;
8……………………….}
9………………………if (pid = = 0)
10……………………… {
11………………………... printf( “Child here ! ”);
12………………………... exit (0);
13……………………….}
14……………………….else
15……………………… {
16………………………… wait (&status);
17………………………… printf(“well done kid ! ”);
18………………………… exit (0);
19……………………….}
20………………….}

Explanation / Answer

1- opening bracket for main() 2- create two integers named 'pid' and 'status'. 3- assign the return value of fork() to pid; in the parent process this will be the process id of the child created. In the child process it will assign 0 to pid. 4- if pid equals -1 that means there was an error in creating a process 5- opening bracket for if-statement 6- tells the user that creating a new process failed 7- exits with an error code, showing that something went wrong 8- closing bracket for if-statement 9- if pid = 0, that means that this is the child process 10- opening bracket for if statement 11- print "Child here!" from the child process 12- exit the child process with no error code 13- closing bracket for if statement 14- if the pid is not 0, meaning it is the parent process 15- opening bracket for else-statement 16- wait for the child process to complete; since status is passed by reference, its value will be changed by the call to wait to w/e status updates it has 17- print "well done kid!" from the parent process 18- exit parent process with no error code 19- closing bracket for else-statement 20- closing bracket for main() things to know: when you call fork(), it creates a new process which creates a copy of all of the current variables, and resumes execution in both the parent and child process at that line. The way you tell them apart is that in the parent process, fork returns the id of the child process created, whereas in the child process it returns 0. A return value of -1 means that a process was not created due to an error.