Signal volume for Linux process communication

Source: Internet
Author: User
Tags semaphore

Semaphore signal Semaphore, and other process communication mode is very different, the main purpose is to protect critical resources. The process can determine whether certain shared resources can be accessed based on it. In addition to access control, it can also be used for process synchronization.


Classification:

Two-value lights: The value of the semaphore can only be 0 or 1, similar to mutual exclusion lock. But the two are different: lights emphasize shared resources, as long as the shared resources are available, other processes can also modify the value of the semaphore, the mutex is more emphasis on the process, the resource-intensive process uses the resources, the process itself must be unlocked. (We often say that the PV operation)

Counting lights: The value of the semaphore can take any non-negative number. (More for producer consumer models)

No matter what kind of signal, when the value of the signal is 0 o'clock, blocking occurs.


Semaphore Usage Related API

int Semget (key_t key, int nsems, int semflg);
Function: Create a new semaphore or get an existing semaphore.
Key: A value of ipc_private means that a new semaphore is about to be created. , the official argument is to use Ftok to generate a key (one that is personally more agreeable to one's own definition).
Nsems: Specifies the number of semaphores that will be included in the open or newly created semaphore set.
Nsems > 0 o'clock, create a new semaphore set that specifies the amount of semaphores in the collection.
Nsems = = 0 o'clock, access an existing collection.
MSGFLG: is a set of flags.
Ipc_creat: If semaphore does not exist, create a shared memory.
IPC_EXCL: Only when the semaphore does not exist, the new semaphore is established, otherwise it generates an error.
This is typically done for this parameter
#define PERM S_IRUSR | S_IWUSR | Ipc_creat
Then take PERM as SEMFLG.
The ID of the semaphore set returned successfully, not successfully returned-1, and set errno.
Note: After the successful execution of the Semget function, a semaphore that is maintained by the kernel with a type of semid_ds struct is generated.
Set, the return value is the lead point that points to the semaphore set. The structure prototype is as follows:
struct Semid_ds {
struct Ipc_perm sem_perm; /* Operation license permission for Semaphore set */
struct SEM *sem_base; /* A pointer to an array of SEM structures, where each semaphore in the current semaphore set corresponds to one of the array elements */
UShort Sem_nsems; /* Number of sem_base arrays */
time_t Sem_otime; /* The last time the semaphore array was successfully modified */
time_t Sem_ctime; /* Successful creation time */
};
struct IPC_PERM
{
__kernel_key_t key; Key values for IPC
__kernel_uid_t uid; Owner's User ID
__kernel_gid_t GID; Group ID of the owner
__kernel_uid_t cuid; User ID of the creator
__kernel_gid_t Cgid; Group ID of creator
__kernel_mode_t mode; Access mode
unsigned short seq; Serial number
};
struct SEM {
UShort Semval; /* Current value of semaphore */
Short Sempid; /* The process ID number of the last time the semaphore was returned */
UShort semncnt; /* Number of processes waiting for semval greater than current value */
UShort semzcnt; /* Wait for Semval to become 0 of the number of processes */
};

int semop (int semid, struct sembuf *sops, unsigned nsops);
Function: Sets the value of the semaphore.
Semid: identifier of the semaphore (return value of the Semget function)
SOPs: A pointer to the semaphore operation structure Array. The structure prototype is as follows:
struct SEMBUF {
unsigned short sem_num; The number of semaphores to operate in the semaphore set,
Short Sem_op; Semaphore operation
Short SEM_FLG; Action specifier
};
If the sem_op is positive, the value is added to the Semval, which is the resource that releases the semaphore control
If Sem_op is 0, then the caller wants to wait until Semval becomes 0, and if Semval is 0 it returns;
If Sem_op is negative, then the caller wants to wait for semval to become greater than or equal to the absolute value of SEM_OP
Note: Semval refers to the value of a semaphore in a semaphore set in the Semid_ds
SEM_FLG: Can be the following values:
Sem_undo The semaphore is automatically released by the process
Ipc_nowait does not block
Nsops: The number of array of semaphore manipulation structures.

int semctl (int semid, int semnum, int cmd, ...);
function function: Control the semaphore information.
Semid: identifier of the semaphore (return value of the Semget function)
Semnum: Is the sequence number of the signal in the collection
CMD: Control command. The following values are desirable:
Setval: Specifies the current value of the semaphore. At this point semval = Val (the description of Val see the fourth parameter that may appear below)
Getval: Gets the current value of the semaphore. (return value of Semctl function)
SETALL: Specifies the value of all semaphores. An array is used at this time to assign all values of the semaphore set (the description of the array looks at the fourth parameter that may appear below)
GETALL: Gets the value of all semaphores. Returns all the values of the semaphore set to the array specified by array. (The description of the array looks at the fourth parameter that may appear below)
Ipc_stat: Gets the state of the semaphore.
Ipc_set: Change the state of the semaphore.
Ipc_rmid: Deleting semaphore identifiers
The fourth parameter is a federated structure that must be customized by the user, and the struct prototype is as follows:
Union Semun
{
int Val; cmd = = Setval
struct Semid_ds *buf//cmd = = Ipc_set or cmd = = Ipc_stat
UShort *array; cmd = = SETALL, or cmd = GETALL
};
Note: The fourth parameter is only used when needed.



Sample program (Simple PV Operation example)


Sem_h.h#ifndef sem_h_h_included#define sem_h_h_included#include <unistd.h> #include <sys/types.h># Include <sys/stat.h> #include <fcntl.h> #include <stdlib.h> #include <stdio.h> #include < string.h> #include <sys/sem.h> #include <errno.h>//new or open signal Operation flag # define PERM        s_irusr | S_IWUSR | ipc_creat//Union Type Semnu, the fourth parameter of the SEMCTL function, union semnu {    int val;    struct Semid_ds *buf;    UShort *array;};/ /Display error message void print_error (int f_line);//Open or create semaphore void Open_sem (void);//Initialize semaphore void Init_sem (void);//signal Volume P operation void SEM Aphore_p (void);//Semaphore v operation void Semaphore_v (void);//delete semaphore void Del_sem (void); #endif//sem_h_h_included

Sem_c.c#include "SEM_H.H"//semaphore Idint sem_id = 0;void print_error (int f_line) {fprintf (stderr, "%s%s%d\n", St Rerror (errno), __file__, f_line);}     void Open_sem (void) {if (sem_id = Semget ((key_t) 1234, 1, PERM)) = =-1) {print_error (__line__);    }}void Init_sem (void) {Union semnu semnu;    Semnu.val = 1;    if (Semctl (sem_id, 0, setval, semnu) = =-1) {print_error (__line__);    }}void semaphore_p (void) {struct sembuf sem_b;    Sem_b.sem_num = 0;    Sem_b.sem_op =-1;    SEM_B.SEM_FLG = Sem_undo;    if (Semop (sem_id, &sem_b, 1) = =-1) {print_error (__line__);    }}void semaphore_v (void) {struct sembuf sem_b;    Sem_b.sem_num = 0;    Sem_b.sem_op = 1;    SEM_B.SEM_FLG = Sem_undo;    if (Semop (sem_id, &sem_b, 1) = =-1) {print_error (__line__);    }}void Del_sem (void) {if (Semctl (sem_id, 0, ipc_rmid) = =-1) {print_error (__line__); }}
sem_1.c#include "sem_h.h" int main (void) {    Open_sem ();    Init_ SEM ();    while (1) {       //P operation, attempt to enter buffer         semaphore_p (); &nbs P     printf ("%d:hello \ n", Getpid ());        sleep (1);         v operation, leaving buffer         SEMAPHORE_V ();   }} 
Sem_2.c#include "sem_h.h" #include <signal.h>int runnig = 1;void handlesignal (int signo) {printf ("dasd\n");      Runnig = 0; Del_sem ();}    int main (void) {if (signal (sigint,handlesignal) ==sig_err) {print_error (__line__);    } Open_sem ();        while (Runnig) {semaphore_p ();        printf ("%d:hello \ n", Getpid ());        Sleep (1);    Semaphore_v (); }}

Test Example:

First execute sem_2 at the command line at this point, the program is not output, because the value of the semaphore is 0, blocked, and then run Sem_1, you will find that the program began to output, and is alternating output.


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Signal volume for Linux process communication

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.