Skip to content

Instantly share code, notes, and snippets.

@nazarov-yuriy
Created April 28, 2015 07:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nazarov-yuriy/d0807e2ac72cb03a9dff to your computer and use it in GitHub Desktop.
Save nazarov-yuriy/d0807e2ac72cb03a9dff to your computer and use it in GitHub Desktop.
#define _GNU_SOURCE
#include <sched.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/wait.h>
#include <sys/sem.h>
#include <sys/ipc.h>
#include <errno.h>
int test(int semid)
{
struct sembuf op = {.sem_num = 0, .sem_op = -1, .sem_flg = SEM_UNDO};
int res = semop(semid, &op, 1);
if(res != -1){
sleep(5);
exit(0);
}
return res;
}
int main(int argc, char **argv)
{
key_t key;
int semid = -1, pid, status, val;
key = ftok(argv[0], 131);
if (key == -1) {
perror("Can't make key");
goto out;
}
semid = semget(key, 1, 0777 | IPC_CREAT | IPC_EXCL);
if (semid == -1) {
perror("Can't get sem");
goto out;
}
if (semctl(semid, 0, SETVAL, 1) == -1) {
perror("Can't set sem value");
goto out;
}
pid = fork();
if (pid == -1) {
perror("Can't fork");
} else if(pid == 0) {
exit(test(semid));
}
waitpid(pid, &status, 0);
if ((val = semctl(semid, 0, GETVAL)) == -1) {
perror("Can't get sem value");
goto out;
}
printf("Semaphore value: %d. Child exit status: %d\n", val, status>>8);
out:
if(semid != -1){
semctl(semid, 1, IPC_RMID);
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment