Skip to content

Instantly share code, notes, and snippets.

@bibstha
Created November 18, 2020 22:16
Show Gist options
  • Save bibstha/75b118db49b9b00bde9bd82e1180ae09 to your computer and use it in GitHub Desktop.
Save bibstha/75b118db49b9b00bde9bd82e1180ae09 to your computer and use it in GitHub Desktop.
sysv semaphore set, increment, decrement, blocking and reading current value.
#include <stdio.h>
#include <stdlib.h>
#include <sys/stat.h>
#include <sys/sem.h>
#include <unistd.h>
union semun { /* Used in calls to semctl() */
int val;
struct semid_ds * buf;
unsigned short * array;
struct seminfo * __buf;
};
void errExit(const char* msg) {
perror(msg);
exit(1);
}
int main(int argc, char* argv[]) {
if (argc < 2 || argc > 3) {
fprintf(stderr, "Invalid arguments: Usage \n %s init-val\n %s semid increment-val\n", argv[0], argv[0]);
exit(1);
}
if (argc == 2) { // Setting initial value
key_t key = ftok(".", 'A');
if (key == -1) {
errExit("ftok");
}
int semid = semget(key, 1, IPC_CREAT | S_IRUSR | S_IWUSR);
if (semid == -1) {
errExit("semget");
}
union semun arg;
arg.val = atoi(argv[1]);
printf("%d, about to set semaphore with id=%d to %d\n", getpid(), semid, arg.val);
if (semctl(semid, 0, SETVAL, arg) == -1) {
errExit("semctl");
}
printf("%d, done settting semaphore with id=%d to %d\n", getpid(), semid, arg.val);
}
else {
int semid = atoi(argv[1]);
int inc_val = atoi(argv[2]);
printf("%d, about to change semaphore id=%d by %d\n", getpid(), semid, inc_val);
struct sembuf o;
o.sem_num = 0;
o.sem_op = inc_val;
o.sem_flg = 0;
if (semop(semid, &o, 1) == -1) {
errExit("semop");
}
printf("%d, done setting semaphore with id=%d to %d\n", getpid(), semid, inc_val);
int semval = semctl(semid, 0, GETVAL);
if (semval == -1) {
errExit("semctl");
}
printf("%d, current value of semaphore with id=%d = %d\n", getpid(), semid, semval);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment