I'm on Sun Solaris, but most of this should be the same regardless of OS. I hope this helps.
- LT
semaphore research in the MAN pages:
man semop
man semctl
man semget
man ipcs
man ipcrm
the include files:
Code:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
A unique key and semaphore struct:
Code:
key_t semkey = 2012;
union semun {
int val;
struct semid_ds *buf;
ushort *array;
} arg;
get semaphore id for use:
Code:
int semflg = IPC_CREAT | 0666; /* create with full access */
int nsems = 1; /* number of concurrent processes to allow */
id = semget(semkey, nsems, semflg); /* "id" is used in the semctl() and semop() functions */
create a semaphore:
Code:
id = semget(semkey, nsems, semflg);
arg.val = 1;
if (semctl(id, 0, SETVAL, arg) < 0)
fprintf(stderr, "semctl create() failed\n");
delete a semaphore:
Code:
id = semget(semkey, nsems, semflg);
if ( semctl(id, 0, IPC_RMID, arg) == -1)
fprintf(stderr, "semctl delete() failed\n");
lock semaphore:
Code:
struct sembuf sbuf;
sbuf.sem_num = 0;
sbuf.sem_op = -1; /* lock it */
sbuf.sem_flg = SEM_UNDO;
if ( semop(id, &sbuf, 1) == -1)
fprintf(stderr, "semop lock() failed\n");
unlock semaphore:
Code:
struct sembuf sbuf;
sbuf.sem_num = 0;
sbuf.sem_op = 1; /* UNLOCK IT */
sbuf.sem_flg = SEM_UNDO;
if ( semop(id, &sbuf, 1) == -1)
fprintf(stderr, "semop unlock() failed\n");