信号量

创建信号量

int sem_creat(key_t key){

int semid = 0;

semid = semget(key,1,0666| IPC_CREAT | IPC_EXCL);

if(semid == -1){

perror("semget");

if(errno == EEXIST){

printf("检测到信号量集已经存在\n");

return 0;

}

}

return semid;

}


打开信号量

int sem_open(key_t key){

int semid = 0;

semid =semget(key,1,0666);

if(semid == -1){

perror("semget");

return -1;

}

return semid;

}


设置信号量的值(资源的个数)

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) */

};

int sem_setval(int semid , int val){

int ret =0;

union semun su;

su.val = val;

ret = semctl(semid,0,SETVAL,su);

return ret;

}

获取信号量的值

int sem_getval(int semid){

int ret =0;

union semun su;

ret = semctl(semid,0,GETVAL,su);

printf("val:%d\n",su.val);

return ret;

}

信号量PV操作

int sem_p(int semid){

struct sembuf buf={0,-1,0};

int ret =0;

ret = semop(semid,&buf,1);

return ret;

}

int sem_v(int semid){

struct sembuf buf={0,1,0};

int ret =0;

ret = semop(semid,&buf,1);

return ret;

}

sembuf结构体

{

unsigned short int sem_num; /* semaphore number */

short int sem_op;  /* semaphore operation */

short int sem_flg;  /* operation flag */

};

struct sembuf buf={0,1,0};

信号量的编好,  pv操作 P-1 V+1 ,操作0阻塞 

你可能感兴趣的:(信号量)