Skip to content

Instantly share code, notes, and snippets.

@fherbine
Last active April 28, 2023 12:58
Show Gist options
  • Save fherbine/78f5263618803071492b78b2f8cd0a4c to your computer and use it in GitHub Desktop.
Save fherbine/78f5263618803071492b78b2f8cd0a4c to your computer and use it in GitHub Desktop.
[Proof Of Concept] IPCc in C
/*
* HOW TO USE ?
*
* 1. Compile the program using `gcc sem_sysV.c`
* 2. Start the processes one by one
* 3. You'll see that only one process will enter the "main loop"
* 4. if you want another process to enter the loop, you must kill the process that is running the loop.
*
*/
// general purpose includes
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <signal.h>
//perms
#include <sys/stat.h>
// IPCs related includes
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
#define PROJ_ID 1
#define KEY_PATH "./key.lock"
#define NSEMS 1
#define P 1
#define V -1
#define T 0
static volatile char keep_running = 1;
void test(int semid)
{
int toto;
struct sembuf buf[2];
buf[0].sem_num = 0;
buf[0].sem_op = T;
buf[0].sem_flg = 0;
buf[1].sem_num = 0;
buf[1].sem_op = P;
buf[1].sem_flg = 0;
if ((toto = semop(semid, buf, 2)) == -1)
{
printf("Error during test: %s\n", strerror(errno));
exit(-1);
}
}
void increment(int semid)
{
struct sembuf buf;
buf.sem_num = 0;
buf.sem_op = P;
buf.sem_flg = 0;
if ((semop(semid, &buf, 1)) == -1)
{
printf("Error during increment: %s\n", strerror(errno));
exit(-1);
}
}
void decrement(int semid)
{
struct sembuf buf;
buf.sem_num = 0;
buf.sem_op = V;
buf.sem_flg = 0;
if ((semop(semid, &buf, 1)) == -1)
{
printf("Error during decrement: %s\n", strerror(errno));
exit(-1);
}
}
void keyboard_interrupt(int dummy)
{
keep_running = 0;
}
int main(int argc, char **argv)
{
int semid;
key_t ipc_key;
signal(SIGINT, keyboard_interrupt);
if ((ipc_key = ftok(KEY_PATH, PROJ_ID)) == -1)
{
printf("cannot acquire key :%s\n", strerror(errno));
exit(-1);
}
if ((semid = semget(ipc_key, NSEMS, IPC_CREAT | S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP )) == -1)
{
printf("Cannot create/get Semaphore: %s\n", strerror(errno));
exit(-1);
}
printf("Get sem, id: %d\n", semid);
if (argc > 1 && !strcmp(argv[1], "destroy"))
{
// Destroying semaphore
semctl(semid, 0, IPC_RMID, 0);
return(0);
}
printf("testing...\n");
test(semid);
while (keep_running) {
printf("execution...\n");
}
printf("decrementing...\n");
decrement(semid);
return (0);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment