I've modified the code to make
Code:#include<unistd.h> #include<sys/types.h> #include<sys/ipc.h> #include<sys/sem.h> #include<stdio.h> int s; void wait() { struct sembuf w={0,-2,0}; printf("\nSemval of %d before wait is %d",getpid(),semctl(s,0,GETVAL)); semop(s,&w,1); printf("\nnSemval of %d after wait is %d",getpid(),semctl(s,0,GETVAL)); } void sigz() { struct sembuf w={0,+2,0}; printf("\nSemval of %d before wait is %d",getpid(),semctl(s,0,GETVAL)); semop(s,&w,1); /*mark1*/printf("\nSemval of %d after signal is %d" , getpid(),semctl (s,0,GETVAL)); } void cs() { printf("\nProcess %d entering cs",getpid()); sleep(2); printf("\nProcesss %d quiting cs",getpid()); sleep(2); } union semnu { int val; struct semid_ds *buf; unsigned short *array; } main() { int i; union semnu ss; s=semget(IPC_PRIVATE,1,0666|IPC_CREAT); ss.val=2; semctl(s,0,SETVAL,ss); fork(); for(i=0;i<3;i++) { wait(); cs(); sigz(); sleep(2); } }
The Output if fine. But the debugging results are strange. Even after doing a signal on the semaphore, the value is still the same ( the line is commented as mark1 ) . And strangely processes is able to enter the critical section inspite of the 0 value of the semaphore !.




Reply With Quote