Skip to content

Instantly share code, notes, and snippets.

@ajithbh
Last active August 29, 2015 14:02
Show Gist options
  • Save ajithbh/b5df3ba2887520ed5df3 to your computer and use it in GitHub Desktop.
Save ajithbh/b5df3ba2887520ed5df3 to your computer and use it in GitHub Desktop.
XSI semaphore locking
void semaphore_lock(int sem_id)
{
int res = 0
struct sembuf sops;
sops.sem_num = 0;
sops.sem_flg = SEM_UNDO;
sops.sem_op = -1;
do {
res = semop(sem_id, &sops, 1);
} while (res == -1 && errno == EINTR);
}
void semaphore_unlock(int sem_id)
{
int res = 0;
struct sembuf sops;
sops.sem_num = 0;
sops.sem_op = 1;
sops.sem_flg = SEM_UNDO;
do {
res = semop(sem_id, &sops, 1);
} while (res == -1 && errno == EINTR);
}
int main(int argc, char *argv[])
{
sem_id = semget(key, 1, IPC_CREATE);
/* initialize semaphore #0 to 1 */
union semun arg;
arg.val = 1;
if (semctl(sem_id, 0, SETVAL, arg) == -1) {
perror("semctl");
exit(1);
}
/* remove semaphore */
if (semctl(sem_id, 0, IPC_RMID, arg) == -1 ) {
perror("semctl");
exit(1);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment