downtown 2016-10-08
Linux System V IPC 信号量
#include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h>
//获取key值, key值是System V IPC的标识符,成功返回key,失败返回-1设errno //同pathname+同 proj_id==>同key_t; key_t ftok(const char *pathname, int proj_id);
pathname :文件名
proj_id: 1~255的一个数,表示project_id
key_t key=ftok(".",100); //“.”就是一个存在且可访问的路径, 100是假设的proj_id if(-1==key) perror("ftok"),exit(-1);
//创建/获取一个信号量集,成功返回semid,失败返回-1 int semget(key_t key, int nsems, int semflg);
nsems: 信号量集的大小/信号量的个数,0表示获取已经存在的信号量集
semflg
//create sem semid=semget(key,1,IPC_CREAT|IPC_EXCL|0664); if(-1==semid) perror("semid"),exit(-1);
//主要用于对指定的信号量集/信号量执行指定的操作,成功返回0,失败返回-1设errno int semctl(int semid, int semnum, int cmd, ...);
semid: 信号量集的编号(哪个信号量集)
semnum: 信号量集的下标(这个信号量集里的哪个信号量)
cmd:具体的操作命令
//_GNU_SOURCE struct seminfo { int semmap; /* Number of entries in semaphore map; unused within kernel */ int semmni; /* Maximum number of semaphore sets */ int semmns; /* Maximum number of semaphores in all semaphore sets */ int semmnu; /* System-wide maximum number of undo structures; unused within kernel */ int semmsl; /* Maximum number of semaphores in a set */ int semopm; /* Maximum number of operations for semop(2) */ int semume; /* Maximum number of undo entries per process; unused within kernel */ int semusz; /* Size of struct sem_undo */ int semvmx; /* Maximum semaphore value */ int semaem; /* Max. value that can be recorded for semaphore adjustment (SEM_UNDO) */ }; //semmsl, semmns, semopm, semmni可以通过/proc/sys/kernel/sem来设置
the fourth argument:
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) */ }; //<sys/sem.h> struct semid_ds { struct ipc_perm sem_perm; /* Ownership and permissions */ time_t sem_otime; /* Last semop time */ time_t sem_ctime; /* Last change time */ unsigned short sem_nsems; /* No. of semaphores in set */ }; //<sys/ipc.h> struct ipc_perm { key_t __key; /* Key supplied to semget(2) */ uid_t uid; /* Effective UID of owner */ gid_t gid; /* Effective GID of owner */ uid_t cuid; /* Effective UID of creator */ gid_t cgid; /* Effective GID of creator */ unsigned short mode; /* Permissions */ unsigned short __seq; /* Sequence number */ };
int res=semctl(semid,0,SETVAL,5); if(-1==res) perror("semctl"),exit(-1); int res=semctl(semid,0,IPC_RMID); if(-1==res) perror("semctl"),exit(-1);
//操作指定的信号量集,成功返回0,失败返回-1设errno int semop(int semid, struct sembuf *sops, unsigned nsops);
semid:信号集的ID(returned by semget())
sops:结构体指针, 既可以指向结构体变量, 也可以指向结构体数组信号量集本质上是若干个信号量的集合, 可以实现对信号量的批处理
struct sembuf{ unsigned short sem_num; //信号量集的下标 short sem_op; //正数表示增加, 0表示不变, 负数表示减小 short sem_flg; //操作标志,默认给0 }
nsops:结构体指针指向的元素个数, 也就是数组的大小