zoukankan      html  css  js  c++  java
  • System V semaphore——demo

    代码
    #include sys/types.h>
    #include sys
    /ipc.h>
    #include sys
    /sem.h>
    union semun{
    int val;
    struct semid_ds *buf;
    unsigned
    short *array;
    struct seminfo *__buf;
    };

    // create the semaphore set,
    // if key is IPC_PRIVATE, the semaphore is anonymous
    int semaphore_create(key_t key, int number)
    {
    return semget(key, number, IPC_CREAT|IPC_EXCL|0666);
    }

    // set all semaphores to val
    int semaphore_setAll(int semid, int number, int val)
    {
    int i;
    union semun initVal;
    unsigned
    short valList[number];
    for (i = 0; i < number; i++)
    {
    valList[i]
    = val;
    }
    initVal.array
    = &valList[0];
    return semctl(semid, 0, SETALL, initVal);
    }

    // get all semaphores to val
    int semaphore_getAll(int semid, unsigned short** val)
    {
    union semun ret;
    ret.array
    = *val;
    return semctl(semid, 0, GETALL, ret);
    }

    // set index-th semaphore to val
    int semaphore_set(int semid, int index, int val)
    {
    union semun un;
    un.val
    = val;
    return semctl(semid, index, SETVAL, un);
    }

    // get index-th semaphore to val
    int semaphore_get(int semid, int index, int *val)
    {
    union semun un;
    un.val
    = *val;
    return semctl(semid, index, GETVAL, un);
    }

    // delete the semaphore set
    int semaphore_del(int semid)
    {
    return semctl(semid, 0, IPC_RMID);
    }

    // v operation, here we just add one for example
    int semaphore_v(int semid, int index)
    {
    // add the semaphore
    struct sembuf operation;
    operation.sem_num
    = index;
    operation.sem_op
    = 1;
    operation.sem_flg
    = SEM_UNDO;
    return semop(semid, &operation, 1);
    }

    // p operation, here just del one for example
    int semaphore_p(int semid, int index)
    {
    struct sembuf operation;
    operation.sem_num
    = index;
    operation.sem_op
    = -1;
    operation.sem_flg
    = SEM_UNDO;
    struct timespec delay;
    delay.tv_sec
    = 2;
    delay.tv_nsec
    = 0;
    return semtimedop(semid, &operation, 1, &delay);
    }
  • 相关阅读:
    家目录,Linux常用命令概述
    Day003_Linux基础——系统目录结构
    Day002_LInux基础_常用命令_001
    Day002_LInux基础_常用命令
    Linux_Day001-002章常用命令
    Linux基础Day001-001章
    pycharm单行及多行注释快捷键
    配置ospf的路由器连通配置静态路由的路由器
    python--闭包
    主机数和可用主机数计算
  • 原文地址:https://www.cnblogs.com/BloodAndBone/p/1939518.html
Copyright © 2011-2022 走看看