Hey ,
I'm trying to implement a semaphore which provides mutual exclusion among two processes to a given critical section on Linux. Below is the code which does that. I had written the code initially without the lines commented as "Check1" and "Check2". The code could not provide any mutual exclusion. I added the two lines explained previously for debugging purposes. After adding the lines, the code started giving the required output. I can't figure out what happened. Commenting the lines and running the code leads to the previous undesired output.
Code:#include<sys/sem.h> #include<sys/ipc.h> #include<stdio.h> #include<unistd.h> int s; signal() { printf("\ns:%d here \n",getpid()); // Check 1 struct sembuf sa={0,1,0}; semop(s,&sa,1); } wait() { printf("\nw:%d here \n",getpid()); //Check 2 struct sembuf sa={0,-1,0}; semop(s,&sa,1); } void cs() // Critical Section { printf("\nProcess%d entering ",getpid()); sleep(1); printf("\nProcess%d exiting ",getpid()); sleep(1); } union semun // The Union Structure for semget { int val; struct semid_ds *buff; unsigned short int *array; } main() { int i; union semun x; int pid; s=semget(IPC_PRIVATE,1,0666|IPC_CREAT); // Creating a single semaphore x.val=1; semctl(s,0,SETVAL,x); // Initializing semaphore's value to be 1 pid=fork(); for(i=0;i<2;i++) { wait(); // Decrement Semaphore cs(); signal(); // Increment Semaphore sleep(1); } }
Does it ring a bell ?...




Reply With Quote