c信号量操作demo
#include <stdio.h> #include <string.h> #include <sys/ipc.h> #include <sys/sem.h> // union semun { // int val; // struct semid_ds *buf; // unsigned short *array; // struct seminfo *__buf; // }; int P(int semid, int semnum) { struct sembuf sops={semnum, -1, SEM_UNDO}; return (semop(semid, &sops, 1)); } int V(int semid, int semnum) { struct sembuf sops = {semnum, +1, SEM_UNDO}; return (semop(semid, &sops, 1)); } void test2(); int main(int argc, char **argv){ printf("argc:%d, argv:%s\n", argc, *argv); test2(); return 0; } void test2(){ int key; int semid,ret; union semun arg; struct sembuf semop; int flag; key = ftok("/tmp", 0x66); arg.val = 3; if (key < 0) { perror("ftok key error"); } semid = semget(key, 3, IPC_CREAT | 0600); if(semid == -1) { perror("create semget error"); } //对0号信号量设置为初始值 ret = semctl(semid, 0, SETVAL, arg); printf("ret:%d\n", ret); if(ret < 0) { perror("ctl sem error"); semctl(semid, 0, IPC_RMID, arg); } //取0号信号量的值 ret = semctl(semid, 0, GETVAL, arg); printf("after semctl setval sem[0].val=[%d]\n", ret); //P操作 flag = P(semid, 0); flag = P(semid, 0); ret = semctl(semid, 0, GETVAL, arg); printf("after P sem[0].val=[%d]\n",ret); //V操作 if (V(semid, 0) < 0) { perror("V operator error"); } if (V(semid, 0) < 0) { perror("V operator error"); } ret = semctl(semid, 0, GETVAL, arg); printf("after v 操作 sem[0].val=%d\n", ret); }
Please call me JiangYouDang!