Exercises for TDDD82, Processes I January 28, 2016 1. Forking processes (based on [1] Excercise 3.4) Using the program shown below, what will be the output at Line A? #include #include #include #include <sys/types.h> <stdio.h> <unistd.h> <stdlib.h> int value = 5; int main() { pid_t pid; pid = fork(); if (pid == 0) { /* child */ value += 15; } else if (pid > 0) { /* parent */ wait(NULL); printf("PARENT: value %d \n", value); /* Line A */ exit(0); } } 2. Which techniques could be used in the program of Exercise 1 in order to get value 20 in the printed output? 1 3. a) The following pseudo code uses the semaphore operations “wait” and “signal” with the aim of achieving mutual exclusion of a shared resource. Does this implementation achieve the desire result. If so, explain why. If not, present a trace from the execution of the program where an undesired behaviour occurs. Process P1 signal(mutex) Critical_section_1 signal(mutex) Non_critical_section_1 end Process P2 wait(mutex) Critical_section_2 signal(mutex) Non_critical_section_2 end b) Explain what happens in the system a. In case process P1 crashes while it is not in the critical section (Non_critical_section_1). b. In case process P2 crashes within the critical section. 4. Mutual Exclusion (based on [1] Excercise 6.1) The first known correct software solution to the critical-section problem for two processes was developed by Dekker. The two processes P0 and P1 , share the following variables: boolean flag[2]; /* initially false */ int turn; /* initially 0 or 1 */ The structure of process Pi (i = 0, 1) is shown below. It uses j 6= i ∈ {0, 1} to refer to the other process’ variables. Sketch a proof that the algorithm satisfies all three requirements for the critical-section problem. 1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: do { flag[i] = TRUE; while (flag[j]) { if (turn == j) { flag[i] = FALSE; while (turn == j) ; //do nothing flag[i] = TRUE; } } //critical section turn = j; flag[i] = FALSE; //remainder section } while (TRUE); 2 5. Deadlock avoidance (Banker’s algorithm). Given the following snapshot of a system: P0 P1 P2 P3 P4 Allocation ---------A B C 0 1 2 1 0 3 2 1 0 4 1 1 1 0 0 Max --A B C 1 2 3 4 1 5 3 3 4 7 2 5 3 1 1 Available --------A B C 2 3 2 a) Is the system in a safe state? b) If process P2 requests the resources (1, 2, 0), can the request be immediately granted? c) If, instead, process P3 requests the resources (1, 1, 1), can the request be immediately granted? References [1] Abraham Silberschatz, Greg Gagne, and Peter Baer Galvin. Operating System Concepts. John Wiley & Sons, seventh edition, 2005. 3