Reputation: 45
I use semget() to get a semaphore, and initialize its VAL to 0, then I want to wait it with semop(), but it directly return. (Another process is designed to get the SEM and release it after some operations)
But if I get a SEM and init its VAL to 0 in a process, and wait it in another process, it works.
Does it mean that a process cannot block itself?
thanks!!!
like this:
int semid = semget(IPC_PRIVATE, 1, IPC_CREAT);
union semun su;
su.val = 0;
semctl(semid, 1, SETVAL, su);
struct sembuf sb;
sb.sem_num = 0;
sb.sem_op = -1;
sb.sem_flg = 0;
semop(semid, &sb, 1);
Upvotes: 2
Views: 2080
Reputation: 384
As far as I can see at the moment you should:
Initialize the semaphore to 1 (su.val)
Call semop with sb.sem_op set to 0 (i. e. wait for counter to drop to zero).
Drop the count in the other process (sem_op = -1).
Because you initialized the semaphore with 0 and called to decrement it by one (semaphores never go below zero), your wait call will succeed and your process won't block. Does that help?
Perhaps this may give additional insight:
http://linuxdevcenter.com/pub/a/linux/2007/05/24/semaphores-in-linux.html?page=2
Upvotes: 1