Why does semop(semid,&wait[1],2); on a set of three semaphores decreases the value of 0th semaphore instead of 1st and 2nd semaphore?
I have a code where I am working on a set of 3 semaphores. I have a two sets
struct sembuf wait[3],signal[3];
I have initialized each one of them. wait is initialized to -1 and signal is initialized to 1
I then set their values as 2 using the function semctl(semid,0,SETALL,2);
which works successfully. I then check if their values are set, and they are set.
Then I do semop(semid,&wait[1],2);
. this should wait on both the semaphores and decrease their values. So I expect the values of three semaphores to be 2,1,1 by this time, but to my surprise it decreased the value of 1st semaphore twice and I see the values as 0,2,2.
Can anyone tell me why is this happening.
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<sys/sem.h>
#include<sys/ipc.h>
#include<sys/types.h>
#include<string.h>
#include<errno.h>
int main(int argc,char *argv[]){
key_t key1 = 12345;
int semid;
unsigned short *semval;
struct sembuf wait[3],signal[3];
semval = (unsigned short*) malloc(sizeof(unsigned short) * 3);
wait[0].sem_num = 0;
wait[0].sem_op = -1;
wait[0].sem_flg = SEM_UNDO;
signal[0].sem_num = 0;
signal[0].sem_op = 1;
signal[0].sem_flg = SEM_UNDO;
wait[1].sem_num = 0;
wait[1].sem_op = -1;
wait[1].sem_flg = SEM_UNDO;
signal[1].sem_num = 0;
signal[1].sem_op = 1;
signal[1].sem_flg = SEM_UNDO;
wait[2].sem_num = 0;
wait[2].sem_op = -1;
wait[2].sem_flg = SEM_UNDO;
signal[2].sem_num = 0;
signal[2].sem_op = 1;
signal[2].sem_flg = SEM_UNDO;
semid = semget(key1,3,IPC_CREAT);
printf("ALLOCATING THE SEMAPHORES = %s\n",strerror(errno));
semval[0] = semval[1] = semval[2] = 2;
semctl(semid,0,SETALL,semval);
printf("SETTING SEMAPHORE VALUES = %s\n",strerror(errno));
se开发者_如何学JAVAmctl(semid,0,GETALL,semval);
printf("Initialized Semaphore values : %d--%d--%d\n",semval[0],semval[1],semval[2]);
semop(semid,&wait[1],2);
printf("WAITING ON SEMAPHORES 2 AND 3 = %s\n",strerror(errno));
semctl(semid,0,GETALL,semval);
printf("VALUES AFTER WAITING ON SEMAPHORES 2 AND 3 : %d--%d--%d\n",semval[0],semval[1],semval[2]);
semctl(semid,0,IPC_RMID);
printf("SEMAPHORE REMOVED = %s\n",strerror(errno));
return 0;
}
and here is the output
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ gcc -g -o sem3 sem3.c
anirudh@anirudh-Aspire-5920:~/Desktop/testing$ sudo ./sem3
ALLOCATING THE SEMAPHORES = Success
SETTING SEMAPHORE VALUES = Success
Initialized Semaphore values : 2--2--2
WAITING ON SEMAPHORES 2 AND 3 = Success
VALUES AFTER WAITING ON SEMAPHORES 2 AND 3 : 0--2--2
SEMAPHORE REMOVED = Success
Finally managed to write a blog on it. http://systemsdaemon.blogspot.com/2011/02/system-v-semaphores-for-babies.html
You used sem_num=0 in all of your parameters.
精彩评论