As with Message Queuing and shared memory, Semaphore sets have their own data structures:
struct Semid_ds {
struct Ipc_perm sem_perm; /* Ownership and Permissions * *
time_t Sem_otime; /* Last SEMOP time * *
time_t Sem_ctime; /* Last Change time * *
unsigned short sem_nsems; /* No. of semaphores in Set * *
};
Similarly, the first entry is also a shared IPC object kernel structure, and the rest is private members.
Each semaphore in a semaphore set has the following associated values:
unsigned short semval; /* Semaphore Value * *
unsigned short semzcnt; * * Waiting for Zero * *
unsigned short semncnt; * * Waiting for increase * *
pid_t Sempid; /* process that did last OP *
That is, each semaphore in the signal set has the above 4 related variables.
1, Semval: The current number of a signal amount of resources
2, semzcnt: When Sem_op (see struct Sembuf) is 0, and the SEMOP function does not set the IPC_NOWAIT flag, and the current semval is not 0, the process will block wait until 4 events occur, specifically man 2 semop, Then semzcnt will add 1, indicating that the resource that waits for this semaphore becomes 0 processes plus 1.
3, semncnt: When Sem_op (see struct Sembuf) < 0, and the SEMOP function does not set the IPC_NOWAIT flag, and the current Semval < |sem_op| , the process blocks waiting until 4 events occur, the Man 2 Semop, and then semncnt adds 1, indicating the number of processes waiting for this semaphore to increase by 1.
4. When the SEMOP function is correctly executed, the sempid parameters of each semaphore are set to process PID that changes this semaphore.
Here are a few semaphore set operations functions:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>
int Semget (key_t key, int nsems, int semflg);
int semctl (int semid, int semnum, int cmd, ...);
int semop (int semid, struct sembuf *sops, unsigned nsops);
Function: Used to create and access a semaphore set
Prototype int semget (key_t key, int nsems, int semflg);
Parameters
Key: The name of the signal set
Nsems: Number of signals in signal concentration
SEMFLG: Consists of nine permission flags, and their usage is the same as the mode mode flag used to create the file
Return value: Successfully returns a non-negative integer, that is, the identifier of the signal set; failed return-1
Function: Used to control semaphore set
Prototype int semctl (int semid, int semnum, int cmd, ...);
Parameters
SEMID: Signal set identification code returned by Semget
Semnum: The serial number of the semaphore in the signal set, numbered starting from 0
CMD: Action to be taken (three desirable values)
The last parameter is union Semun, the specific members vary according to CMD.
Union Semun {
int Val; /* Value for Setval * *
struct Semid_ds *buf; /* Buffer for Ipc_stat, Ipc_set * *
unsigned short *array; /* Array for GETALL, SetAll * *
struct Seminfo *__buf; /* Buffer for Ipc_info (linux-specific) * *
};
Return value: successful return 0; failure return-1