Create successful ePaper yourself
Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.
Processes II<br />
Kernel data structures for a semaphore set<br />
#include <br />
#include <br />
#include <br />
semid<br />
sem-perm<br />
sem_base<br />
sem_nsems<br />
sem_otime<br />
sem ctime<br />
semval<br />
sempid<br />
semncnt<br />
semzcnt<br />
semval<br />
sempid<br />
semncnt<br />
semzcnt<br />
[0]<br />
[0]<br />
[0]<br />
[0]<br />
[1]<br />
[1]<br />
[1]<br />
[1]<br />
int semget(key_t key, int nsems, int semflag);<br />
semflag<br />
0400 SEM_R alter by owner<br />
0200 SEM_A read by owner<br />
0040 SEM_R >> 3 alter by group<br />
0020 SEM_A >> 3 alter by group<br />
0004 SEM_R >> 6 read by world<br />
0002 SEM_A >> 6 alter by world<br />
IPC_CREAT<br />
IPC_EXCL<br />
int semop(int semid, struct sembuf **opsptr, unsigned int nops);<br />
struct sembuf {<br />
ushort sem_num; /* semaphore # */<br />
short sem_op; /* semaphore operation */<br />
short sem_flg; /* operation flags */<br />
};<br />
Semaphore operations:<br />
- if sem_op > 0, sere_val is added to semaphore value (release of resources)<br />
- if sem_op = 0, caller waits until semaphore value = 0<br />
- if sem_op < 0, caller waits until semaphore value >= absolute of sem_op<br />
int semctl(int semid, int semnum, int cmd, union semnum arg);<br />
union semun {<br />
int val; /* used for SETVAL only */<br />
struct semid_ds *buffi /* used for IPC_STAT & IPC_SET */<br />
ushort *arrarY; /* used for IPC_GETALL & IPC_SETALL */<br />
} arg;<br />
File Locking <strong>with</strong> Semaphores<br />
To lock <strong>the</strong> semaphore call semop to do two operations atomically. First, wait for sem#0 to become 0, <strong>the</strong>n<br />
secondly increment sem#0 by 1.<br />
To unlock <strong>the</strong> resource, call semop to decrement sem#0 by 1. Explicitly set IPC_NOWAIT, so that cannot wait if<br />
"impossible condition" occurs.<br />
With System V, it is hard to initialize a semaphore to a value o<strong>the</strong>r than zero.<br />
If <strong>the</strong> process aborts for any reason while it has <strong>the</strong> lock, <strong>the</strong> semaphore value is left at one.<br />
Any o<strong>the</strong>r process that tries to obtain <strong>the</strong> lock waits forever when it does <strong>the</strong> locking semop that first waits for <strong>the</strong><br />
value to become zero.<br />
System V solution is to tell <strong>the</strong> kernel (when obtaining lock) that if this process terminates before releasing lock,<br />
release it for <strong>the</strong> process.<br />
139