Question: EASY unix/C assignment: Review this code and answer the 4 questions about them afterwards.. Below is a simple example, fork.c, involving the fork() call. /*

EASY unix/C assignment:

Review this code and answer the 4 questions about them afterwards..

Below is a simple example, fork.c, involving the fork() call. /* Slight modification of Richard Stevens example from "Advanced Programming in the UNIX Environment" */ #include #include #include #include int globalVar = 6; /* external variable in the initialized data */ char buf[] = "Write to the standard output "; int main(void){ int localVar; /* local variable in the initialized data */ pid_t pid; localVar = 88; if (write(STDOUT_FILENO, buf, sizeof(buf)-1) != sizeof(buf)-1){ printf("write error"); exit(1); } printf("Now, the fork starts "); if ( (pid = fork()) < 0){ printf("fork error "); exit(1); } else if (pid == 0) { globalVar++; localVar++; } else sleep(2); printf("pid = %d, globalVar = %d, localVar = %d ", getpid(), globalVar, localVar); exit(0); }

QUESTIONS:

1. What are the process ids for the child and the parent processes? 2. Which parts are done by both processes, by the child only, and by the parent only? 3. Why does only the child process increment the two variables, i.e., globalVar and localVar? Why are both of them affected? 4. Which process(es), child and/or parent, execute(s) the sleep command? Why is that?

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!