Solutions-Mid Term
Solutions-Mid Term
Solutions-Mid Term
#include <unistd.h>
#include <sys/wait.h>
#include <stdio.h>
#include <signal.h>
main()
{
int child_id,grandson_id,myID;
child_id = fork();
if(child_id == 0) /*child process*/
{
myID=getpid();
printf("the child process ID is: %d\n", myID);
grandson_id =fork();
if(grandson_id ==0) /*grandchild process*/
{
printf("grandchild process \n");
exit();
}
sleep(120);
}
sleep(60);
kill(0, SIGKILL);
/* Kill all the child process and itself */
}
(b) Show the memory layout for parent and child after the parents first fork() call
Please refer to lecture notes for processes.
C. Synchronization (20%)
(a) The following algorithm is used to synchronize two processes. Please
comment if it works and if it meets all the requirement of correct synchronization.
Shared Variables :
//Boolean flag[2]; //retain state about each thread
// initially flag[0] = flag[1] = false.
flag[i] = true then P(i) ready to enter its critical section
Process P(i)
do {
flag[i] = true;
While (flag[j]);
Critical section
flag [i] = false;
remainder section
}while (1)
The algorithm provides mutual exclusion but does not meet the progress
requirement of correct synchronization.
Consider the following execution sequence :
T(0): P(i) sets flag[i] = true
T(1): P(j) sets flag[j] = true
Now P(i) and P(j) are looping forever in their respective while statements. Thus
this algorithm is dependent on the exact timing of the two processes.
R2
P2
R1
P1