Semaphores are not used to exchange a large amount of data but they
provide synchronization among processes.
There are 3 (logical) types of semaphores:

  • Binary Semaphore: have a value of 0 or 1
  • Counting semaphore – has a value >= 0
  • Set of counting semaphores – one or more semaphores, each of which
    is a counting semaphore.

    There are 2 basic operations performed with semaphores:

  • Wait – waits until the semaphore is > 0, then decrements it.
  • Post – increments the semaphore, which wakes waiting processes.

    A semaphore is created by using the semget(). There were various that
    can be performed on the semaphore by using the functions like semop(),
    semctl() etc.

Brief Synopsis of :

  • semget(): It gets a semaphore set identifier
    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/sem.h>

    int semget(key_t key, int nsems, int semflg);

    This function returns the semaphore set identifier associated with the
    argument key. A new set of nsems semaphores is created if key has the
    value IPC_PRIVATE or if no existing semaphore set is associated to key
    and IPC_CREAT is asserted in semflg (i.e. semflg & IPC_CREAT isn’t
    zero).

    The presence in semflg of the fields IPC_CREAT and IPC_EXCL plays the
    same role, with respect to the existence of the semaphore set, as the
    presence of O_CREAT and O_EXCL in the mode argument of the open(2)
    system call: i.e. the semget function fails if semflg asserts both
    IPC_CREAT and IPC_EXCL and a semaphore set already exists for key.

    Upon creation, the low-order 9 bits of the argument semflg define the
    access permissions (for owner, group and others) for the semaphore
    set. These bits have the same format, and the same meaning, as the
    mode argument in the open(2) or creat(2) system calls (though the
    execute permissions are not meaningful for semaphores, and write
    permissions mean permission to alter semaphore values).

  • semctl(): semaphore control operations

    #include <sys/types.h>
    #include <sys/ipc.h>
    #include <sys/sem.h>

    int semctl(int semid, int semnum, int cmd, …);

    semctl() performs the control operation specified by cmd on the
    semaphore set identified by semid, or on the semnum-th semaphore of
    that set. (The semaphores in a set are numbered starting at 0.)

    This function has three or four arguments, depending on cmd. When
    there are four, the fourth has the type union semun. The calling
    program must define this union as follows:
    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) */
    };

    The semid_ds data structure is defined in <sys/sem.h>.

Advertisements