linux进程间信号量的等待投递

linux进程间信号量的等待投递,第1张

每个信号量都具有一个非负的值,且信号量支持等待和投递操作。系统调用 semop 实现了这两个操作。它的第一个参数是信号量的标识符,第二个参数是一个包含 struct sembuf 类型元素的数组;这些元素指明了您希望执行的操作。第三个参数是这个数组的长度。结构体sembuf中包含如下字段:

sem_num将要执行操作的信号量组中包含的信号量数量。 sem_op是一个指定了操作类型的整数。 如果sem_op是一个正整数,则这个值会立刻被加到信号量的值上。 [BR]如果 sem_op 为负,则将从信号量值中减去它的绝对值。如果这将使信号量的值小于零,则这个操作会导致进程阻塞,直到信号量的值至少等于操作值的绝对值(由其它进程增加它的值)。 [BR]如果 sem_op 为0,这个操作会导致进程阻塞,直到信号量的值为零才恢复。 sem_flg 是一个符号位。指定 IPC_NOWAIT 以防止操作阻塞;如果该操作本应阻塞,则semop调用会失败。如果为sem_flg指定SEM_UNDO,Linux会在进程退出的时候自动撤销该次操作。 代码 5.4 展示了二元信号量的等待和投递操作。

代码 5.4 (sem_pv.c)二元信号量等待和投递操作

#include <sys/types.h>

#include <sys/ipc.h>

#include <sys/sem.h>

/* 等待一个二元信号量。阻塞直到信号量的值为正,然后将其减1 */

int binary_semaphore_wait (int semid)

{

struct sembuf operations[1]

/* 使用(且仅使用)第一个信号量 */

operations[0].sem_num = 0

/* 减一。 */

operations[0].sem_op = -1

/* 允许撤销操作 */

operations[0].sem_flg = SEM_UNDO

return semop (semid, operations, 1)

}

/* 对一个二元信号量执行投递操作:将其值加一。 这个操作会立即返回。*/

int binary_semaphore_post (int semid)

{

struct sembuf operations[1]

/* 使用(且仅使用)第一个信号量 */

operations[0].sem_num = 0

/* 加一 */

operations[0].sem_op = 1

/* 允许撤销操作 */

operations[0].sem_flg = SEM_UNDO

return semop (semid, operations, 1)

}

指定 SEM_UNDO 标志解决当出现一个进程仍然持有信号量资源时被终止这种特殊情况时可能出现的资源泄漏问题。当一个进程被有意识或者无意识地结束的时候,信号量的值会被调整到“撤销”了所有该进程执行过的操作后的状态。例如,如果一个进程在被杀死之前减小了一个信号量的值,则该信号量的值会增长。

信号量:一个整数;

大于或等于0时代表可供并发进程使用的资源实体数;

小于0时代表正在等待使用临界区的进程数;

用于互斥的信号量初始值应大于0;

只能通过P、V原语操作而改变;

信号量元素组成:

1、表示信号量元素的值;

2、最后操作信号量元素的进程ID

3、等待信号量元素值+1的进程数;

4、等待信号量元素值为0的进程数;

二、主要函数

1.1 创建信号量

int semget(

key_t key, //标识信号量的关键字,有三种方法:1、使用IPC——PRIVATE让系统产生,

// 2、挑选一个随机数,3、使用ftok从文件路径名中产生

int nSemes, //信号量集中元素个数

int flag //IPC_CREAT;IPC_EXCL 只有在信号量集不存在时创建

)

成功:返回信号量句柄

失败:返回-1

1.2 使用ftok函数根据文件路径名产生一个关键字

key_t ftok(const char *pathname,int proj_id)

路径名称必须有相应权限

1.3 控制信号量

int semctl(

int semid, //信号量集的句柄

int semnum, //信号量集的元素数

int cmd, //命令

/*union senum arg */... //

)

成功:返回相应的值

失败:返回-1

命令详细说明:

cmd: IPC_RMID 删除一个信号量

IPC_EXCL 只有在信号量集不存在时创建

IPC_SET 设置信号量的许可权

SETVAL 设置指定信号量的元素的值为 agc.val

GETVAL 获得一个指定信号量的值

GETPID 获得最后操纵此元素的最后进程ID

GETNCNT 获得等待元素变为1的进程数

GETZCNT 获得等待元素变为0的进程数

union senum 定义如下:

union senum{

int val

struct semid_ds *buf

unsigned short * array

}agc

其中 semid_ds 定义如下:

struct semid_ds{

struct ipc_pem sem_pem //operation pemission struct

time_t sem_otime //last semop()time

time_t sem_ctime //last time changed by semctl()

struct sem *sembase //ptr to first semaphore in array

struct sem_queue *sem_pending//pending operations

struct sem_queue *sem_pending_last//last pending operations

struct sem_undo *undo //undo requests on this arrary

unsigned short int sem_nsems//number of semaphores in set

}

1.4 对信号量 +1 或 -1 或测试是否为0

int semop(

int semid,

struct sembuf *sops, //指向元素操作数组

unsigned short nsops //数组中元素操作的个数

)

结构 sembuf 定义

sembuf{

short int sem_num//semaphore number

short int sem_op//semaphore operaion

short int sem_flg //operation flag

}

三、例子:

2.1 服务器

#include <sys/sem.h>

#include <sys/ipc.h>

#define SEGSIZE 1024

#define READTIME 1

union semun {

int val

struct semid_ds *buf

unsigned short *array

} arg

//生成信号量

int sem_creat(key_t key)

{

union semun sem

int semid

sem.val = 0

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

if (-1 == semid){

printf("create semaphore error\n")

exit(-1)

}

semctl(semid,0,SETVAL,sem)

return semid

}

//删除信号量

void del_sem(int semid)

{

union semun sem

sem.val = 0

semctl(semid,0,IPC_RMID,sem)

}

//p

int p(int semid)

{

struct sembuf sops={0,+1,IPC_NOWAIT}

return (semop(semid,&sops,1))

}

//v

int v(int semid)

{

struct sembuf sops={0,-1,IPC_NOWAIT}

return (semop(semid,&sops,1))

}

int main()

{

key_t key

int shmid,semid

char *shm

char msg[7] = "-data-"

char i

struct semid_ds buf

key = ftok("/",0)

shmid = shmget(key,SEGSIZE,IPC_CREAT|0604)

if (-1 == shmid){

printf(" create shared memory error\n")

return -1

}

shm = (char *)shmat(shmid,0,0)

if (-1 == (int)shm){

printf(" attach shared memory error\n")

return -1

}

semid = sem_creat(key)

for (i = 0i <= 3i++){

sleep(1)

p(semid)

sleep(READTIME)

msg[5] = '0' + i

memcpy(shm,msg,sizeof(msg))

sleep(58)

v(semid)

}

shmdt(shm)

shmctl(shmid,IPC_RMID,&buf)

del_sem(semid)

return 0

//gcc -o shm shm.c -g

}

2.2 客户端

#include <sys/sem.h>

#include <time.h>

#include <sys/ipc.h>

#define SEGSIZE 1024

#define READTIME 1

union semun {

int val

struct semid_ds *buf

unsigned short *array

} arg

// 打印程序执行时间

void out_time(void)

{

static long start = 0

time_t tm

if (0 == start){

tm = time(NULL)

start = (long)tm

printf(" now start ...\n")

}

printf(" second: %ld \n",(long)(time(NULL)) - start)

}

//创建信号量

int new_sem(key_t key)

{

union semun sem

int semid

sem.val = 0

semid = semget(key,0,0)

if (-1 == semid){

printf("create semaphore error\n")

exit(-1)

}

return semid

}

//等待信号量变成0

void wait_v(int semid)

{

struct sembuf sops={0,0,0}

semop(semid,&sops,1)

}

int main(void)

{

key_t key

int shmid,semid

char *shm

char msg[100]

char i

key = ftok("/",0)

shmid = shmget(key,SEGSIZE,0)

if(-1 == shmid){

printf(" create shared memory error\n")

return -1

}

shm = (char *)shmat(shmid,0,0)

if (-1 == (int)shm){

printf(" attach shared memory error\n")

return -1

}

semid = new_sem(key)

for (i = 0i <3i ++){

sleep(2)

wait_v(semid)

printf("Message geted is: %s \n",shm + 1)

out_time()

}

shmdt(shm)

return 0

// gcc -o shmc shmC.c -g

}

这是sys/sem.h文件的内容

/* @(#) sem.h 1.3 1/27/86 17:47:09 */

/*ident "@(#)cfront:incl/sys/sem.h 1.3"*/

/*

** IPC Semaphore Facility.

*/

/*

** Implementation Constants.

*/

#define PSEMN (PZERO + 3) /* sleep priority waiting for greater value */

#define PSEMZ (PZERO + 2) /* sleep priority waiting for zero */

/*

** Permission Definitions.

*/

#define SEM_A 0200 /* alter permission */

#define SEM_R 0400 /* read permission */

/*

** Semaphore Operation Flags.

*/

#define SEM_UNDO 010000 /* set up adjust on exit entry */

/*

** Semctl Command Definitions.

*/

#define GETNCNT 3 /* get semncnt */

#define GETPID 4 /* get sempid */

#define GETVAL 5 /* get semval */

#define GETALL 6 /* get all semval's */

#define GETZCNT 7 /* get semzcnt */

#define SETVAL 8 /* set semval */

#define SETALL 9 /* set all semval's */

/*

** Structure Definitions.

*/

/*

** There is one semaphore id data structure for each set of semaphores

** in the system.

*/

struct semid_ds {

struct ipc_perm sem_perm/* operation permission struct */

struct sem *sem_base/* ptr to first semaphore in set */

ushort sem_nsems/* # of semaphores in set */

time_t sem_otime/* last semop time */

time_t sem_ctime/* last change time */

}

/*

** There is one semaphore structure for each semaphore in the system.

*/

struct sem {

ushort semval /* semaphore text map address */

short sempid /* pid of last operation */

ushort semncnt/* # awaiting semval >cval */

ushort semzcnt/* # awaiting semval = 0 */

}

/*

** There is one undo structure per process in the system.

*/

struct sem_undo {

struct sem_undo *un_np/* ptr to next active undo structure */

short un_cnt/* # of active entries */

struct undo {

short un_aoe/* adjust on exit values */

short un_num/* semaphore # */

int un_id/* semid */

} un_ent[1]/* undo entries (one minimum) */

}

/*

** semaphore information structure

*/

struct seminfo {

int semmap, /* # of entries in semaphore map */

semmni, /* # of semaphore identifiers */

semmns, /* # of semaphores in system */

semmnu, /* # of undo structures in system */

semmsl, /* max # of semaphores per id */

semopm, /* max # of operations per semop call */

semume, /* max # of undo entries per process */

semusz, /* size in bytes of undo structure */

semvmx, /* semaphore maximum value */

semaem /* adjust on exit max value */

}

/*

** User semaphore template for semop system calls.

*/

struct sembuf {

ushort sem_num/* semaphore # */

short sem_op /* semaphore operation */

short sem_flg/* operation flags */

}

//

union semum {

int val

struct semid_ds *bf

ushort *array

} arg

extern int semctl (int, int, int, semum),

semget (key_t, int, int),

semop (int, sembuf**, int)


欢迎分享,转载请注明来源:夏雨云

原文地址:https://www.xiayuyun.com/zonghe/150242.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2023-03-21
下一篇2023-03-21

发表评论

登录后才能评论

评论列表(0条)

    保存