linux中不同进程之间使用共享库访问底层资源,同步锁

semget函数是Unix/Linux系统中的一个系统调用函数,用于获取一个信号量集的标识符(也称为信号量集ID)。
它通常与其他信号量函数(如semop、semctl)一起使用,用于实现进程间同步和互斥。

typedef int __kernel_key_t;
typedef __kernel_key_t		key_t;

int semget(key_t key, int nsems, int semflg);
RETURN VALUE
       If successful, the return value will be the semaphore set identifier (a nonnegative integer), otherwise, -1 is returned, with errno indicating the error.


struct sembuf _lock = {0, -1, SEM_UNDO};
struct sembuf _unlock = {0, 1, SEM_UNDO};
//取值说明
SEM_UNDO: 无论进程进程结束时,都将还原此操作的 sem_op 值
-1: 申请信号量,加锁,信号量-11: 释放信号量,信号量+10:  Each  operation  is  performed on the sem_num-th semaphore of the semaphore set, 
where the first semaphore of the set is numbered 0.  There are three types of operation, 
distin‐ guished by the value of sem_op.

//init
int semid = semget((65535 + 10), 1, IPC_CREAT | IPC_EXCL | 0777); //根据key创建信号量
union semun sem_val;

memset(&sem_val, 0 , sizeof(union semun ));
sem_val.val = 1;
semctl(semid, 0, SETVAL, sem_val); //初始化信号量值

//lock 
semop(semid, &_lock, 1);

//unkock 
semop(semid, &_unlock, 1);



EXAMPLE
       The following code segment uses semop() to atomically wait for the value of 
       semaphore 0 to become zero, and then increment the semaphore value by one.

           struct sembuf sops[2];
           int semid;

           /* Code to set semid omitted */

           sops[0].sem_num = 0;        /* Operate on semaphore 0 */
           sops[0].sem_op = 0;         /* Wait for value to equal 0 */
           sops[0].sem_flg = 0;

           sops[1].sem_num = 0;        /* Operate on semaphore 0 */
           sops[1].sem_op = 1;         /* Increment value by one */
           sops[1].sem_flg = 0;

           if (semop(semid, sops, 2) == -1) {
               perror("semop");
               exit(EXIT_FAILURE);
           }

你可能感兴趣的:(linux内核,linux,算法,运维)