Linux interprocess communication-semaphore

Source: Internet
Author: User
Tags new set semaphore

When multiple process tables access a resource on the system simultaneously, such as writing a record of a database at the same time, or modifying a file at the same time, it is necessary to consider the synchronization problem in the city to ensure that only one process can have exclusive access to the resource at any one time. Typically, the code for a program's access to a shared resource is just a short one, and you are the piece of code that triggers a race condition between processes. We call this code a critical section, or a critical section.

A semaphore is a special variable that only takes a natural number and supports only two operations: Waiting (wait) and signal (signal), both of which are more commonly called P, v operations. Assuming there is a semaphore SV, then the P and V operations on it have the following meanings:

L P (SV), if the value of SV is greater than 0, it is reduced by 1: If the value of SV is 0, the execution of the process is suspended.

L V (SV), if there are other processes waiting for the SV two to hang, then the star is changed, if not, the SV plus 1.

The semaphore API mainly consists of 3 system calls: Semget, Semop, and Semctl. They are designed to operate a set of semaphores, the set of semaphores, rather than a single semaphore.

#include <sys/sem.h>int semget (key_t key, int num_sems, int sem_flags), int semop (int sem_id, struct sembuf *sem_ops, size_t num_sem_ops); int semctl (int sem_id, int sem_num, int command, ...);

L semget function Call creates a new semaphore set or gets a semaphore that exists. The key parameter is a key value that identifies a globally unique semaphore set, just as the file name globally uniquely identifies a document. The process to communicate through semaphores requires the same key value to be used to create or obtain the semaphore.

The Num_sems parameter specifies the number of semaphores in the semaphore set to be created or obtained. If the semaphore is created, the value must be specified, or it can be set to 0 if it is getting the semaphore that already exists

The Sem_flags parameter specifies a set of flags. Its 9 bits at the low end are the permissions of the semaphore, in the same format and meaning as the system calls the open mode parameter. We can do a bitwise "or" operation with the IPC_CREAT flag, even if the semaphore exists, Semget will not error. We can also use the ipc_creat and IPC_EXCL flags to ensure that a new set of unique semaphore sets is created, and if the semaphore is present, Semget returns an error and sets errno to Eexist.

Semget returns a positive integer when the call succeeds, which is the identifier of the semaphore set, returns 1 on failure, and sets the errno


L semop function Changes the value of the semaphore, that is, performing p and V operations

The sem_id parameter is the semaphore set identifier returned by the Semget call to specify the set of target semaphores to be manipulated.

The Sem_ops parameter points to an array of SEMBUF structures, defined as follows:

struct sembuf{    unsigned short int sem_num;    short int sem_op;    short int sem_flg;};

Sem_num is the number of semaphores in the semaphore set, like an array, starting from 0.

SEM_OP Specifies the action type, with an optional value of positive integer, 0, negative integer. Each type of operational behavior is also affected by SEM_FLG.

The optional values for SEM_FLG are ipc_nowait, Sem_undo. Ipc_nowait means that the SEMOP call returns immediately, similar to non-blocking, regardless of whether the semaphore operation is successful or not. Sem_undo refers to canceling an ongoing SEMOP operation when the process exits.

The Num_sem_ops parameter specifies the number of operations to be performed, that is, the number of sem_ops in the array. Semop each member of an array is executed sequentially in the order of arrays, which is an atomic operation.

SEMOP returns 0 on success, returns 1 on failure and sets errno


The L semctl function allows the caller to directly manipulate the semaphore

The sem_id parameter is the semaphore set identifier returned by the Semget call to specify the set of semaphores to be manipulated.

The Sem_num parameter specifies the number of semaphores to be manipulated in the semaphore set.

The command parameter specifies the commands to execute.

Some commands require a 4th argument. It is defined by the user, but the recommended format is given in sys/sem.h:

Union semun{    int val;                         For setval command    struct semid_ds *buf;             For Ipc_stat and Ipc_set commands    unsigned short *array;            For GetAll and SetAll command    struct seminfo *__buf;            for Ipc_info commands};
The return value of Sem_ctl success is determined by the command parameter, which returns 1 on failure and sets the errno


Special Key Values ipc_private ( key parameter of the Semget function )

Semget callers can give them Key parameter to pass a special key value ipc_pricate ( Its value is 0) , so whether or not the semaphore already exists, Semget will create a new semaphore. The semaphore created with this key value is not private to the process, as other names claim. Other processes, especially child processes, also have methods to access this semaphore

Examples of programs that use Ipc_private

#include <sys/sem.h> #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include < sys/wait.h> #define ERR_SYS (msg) do {perror (msg); exit ( -1),} while (0) union semun{int val;struct Semid_ds *buf;unsigne d Short int *array;struct seminfo * __BUF;};  void PV (int sem_id, int op) {struct Sembuf sem_b;sem_b.sem_num = 0;sem_b.sem_op = OP;SEM_B.SEM_FLG = Sem_undo;semop (sem_id, &sem_b, 1);} int main (void) {int sem_id = Semget (ipc_private, 1, 0666);/* The semaphore set size is 1 */union semun sem_un;sem_un.val = 1;/* The value is 2 o'clock, which indicates that you can At the same time two processes perform p operations (i.e. 1 operations) */semctl (sem_id, 0, Setval, Sem_un); /* Operate the first signal in the semaphore set */pid_t pid = fork (), if (PID < 0) Err_sys ("fork"), else if (PID = = 0) {PV (sem_id,-1);p rintf ("Child get t He sem and would sleep 5s.\n "); Sleep (5);p V (sem_id, 1); exit (0);} ELSE{PV (sem_id,-1);p rintf ("Parent get the SEM and would sleep 5s.\n"); Sleep (5);p V (sem_id, 1);} Waitpid (PID, NULL, 0); Semctl (sem_id, 0, Ipc_rmid, sem_un); return 0;}

Reference:

1, "Linux High Performance Server programming," The 13th chapter multi-process programming/signal Volume

2, Linux multi-process programming

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

Linux interprocess communication-semaphore

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.