Linux系统调用--semctl函数详解

来源:互联网 发布:网络潮州歌曲大全100首 编辑:程序博客网 时间:2024/06/04 18:15

来源:http://club.cn.yahoo.com/bbs/threadview/1200062866_109__pn1.html

【semctl系统调用】   
    
功能描述: 
在指定的信号集或信号集内的某个信号上执行控制操作。

  
用法:  
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/sem.h>

int semctl(int semid, int semnum, int cmd, ...);


参数:   
semid:信号集的标识符,即是信号表的索引。
semnum:信号集的索引,用来存取信号集内的某个信号。
cmd:需要执行的命令,有效值有

IPC_STAT //将与semid关联的内核数据结构拷贝到由arg.buf指针指向的内存区。
IPC_SET //将由arg.buf指针指向的semid_ds的一些成员写入相关联的内核数据结构,同时更新它的sem_ctime成员。
IPC_RMID //立即删除信号集,唤醒所有被阻塞的进程。
IPC_INFO //Linux特有命令,返回系统范围内关于信号集的制约和其它参数,并存放在arg.__buf指向的内存区。其结构形态如下:

struct  seminfo {
    int semmap;  /* # of entries in semaphore map; unused */
    int semmni;  /* Max. # of semaphore sets */
    int semmns;  /* Max. # of semaphores in all semaphore sets */
    int semmnu;  /* System-wide max. # of undo structures; unused */
    int semmsl;  /* Max. # of semaphores in a set */
    int semopm;  /* Max. # of operations for semop() */
    int semume;  /* Max. # of undo entries per process; unused */
    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) */
};

SEM_INFO //返回和IPC_INFO相同的信息,不同点有:semusz字段包含有当前系统存在的信号集总量。semaem字段包含有系统内所有信号集的信号总量。
SEM_STAT //返回和IPC_STAT相同的信息。不过参数semid不是一个信号集标识,而是内核内部维持所有信号集信息的数组索引。
GETALL //将所有信号的值存入semun.array中。
GETNCNT //等待信号值增加的进程的总数。
GETPID //前一个对此信号进行操作的进程的识别码。
GETVAL //根据semnun返回信号的值。
GETZCNT //等待信号值变为0的进程的总数。
SETALL //将所有semun.array的值设定到信号集中。
SETVAL //根据semun设定信号的值。

...:对于不同的命令,可能需要用到也可能不需要,是一个联合体,原型如下

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) */
};
  
semid_ds结构体定义在<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 */
};

ipc_perm结构体定义在<sys/ipc.h>,原型如下

struct ipc_perm {
    key_t key;            /* Key supplied to semget() */
    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 */
};

          

返回说明:   
成功执行时,根据不同的命令返回不同的非负值

GETNCNT //返回semncnt的值
GETPID  //返回sempid的值
GETVAL  //返回semval的值
GETZCNT //返回semzcnt的值
IPC_INFO //返回内核内部关于信号集信息的最大可用入口索引 
SEM_INFO //如同IPC_INFO.
SEM_STAT //返回信号集标识
剩下的命令返回0。


失败返回-1,errno被设为以下的某个值   
EACCES:访问出错,权能不允许
EFAULT:arg.buf 或 arg.array所指的空间不可访问
EIDRM:信号集已被删除
EINVAL;参数无效
EPERM:权能不允许
ERANGE:给出的参数无效

0 0
原创粉丝点击