2
3#include<sys/sem.h>
4#include<sys/ipc.h>
5
6#define SEGSIZE 1024
7#define READTIME 1
8
9union semum
10{
11int val
12struct semid_ds *buf
13unsigned short *array
14}arg
15
16/* 创建信号量 */
17int sem_creat(key_t key)
18{
19union semun sem
20int semid
21sem.val = 0
22semid = semget(key, 1, IPC_CREAT | 0666)
23
24if (semid == -1)
25{
26printf("Create semaphore error\n")
27exit(-1)
28}
29
30semctl(semid, 0, SETVAL, sem)
31
32return semid
33}
34
35/* 删除信号量*/
36int del_sem(int semid)
37{
38union semun sem
39sem.val = 0
40semctl(semid, 0, IPC_RMID, sem)
41}
42
43/* 信号量的P操作,使得信号量的值加1 */
44int p(int semid)
45{
46struct sembuf sops = {0,
47 +1,
48 IPC_NOWAIT
49 }
50
51return (semop(semid, &sops, 1))
52}
53
54/* 信号量的v操作,使得信号量的值减1 */
55int v(int semid)
56{
57struct sembuf sops = {0,
58 -1,
59 IPC_NOWAIT
60 }
61
62return (semop(semid, &sops, 1))
63}
64
65/* server主程序 */
66int main(int argc, char **argv)
67{
68key_tkey
69int shmid, semid
70char *shm
71char msg[7] = "-data-"
72char i
73struct semid_ds buf
74
75key = ftok("/", 0)
76shmid = shmget(key, SEGSIZE, IPC_CREAT|0604)
77
78if shmid == -1)
79{
80printf(" create shared memory error\n")
81return -1
82}
83
84shm = (char *)shmat(shmid, 0, 0)
85if (-1 == (int)shm)
86{
87printf(" attach shared memory error\n")
88return -1
89}
90
91semid = sem_creat(key)
92
93for (i = 0i <= 3i++)
94{
95sleep(1)
96p(semid)
97sleep(READTIME)
98msg[5] = '0' + i
99memcpy(shm,msg,sizeof(msg))
100sleep(58)
101v(semid)
102}
103
104shmdt(shm)
105
106shmctl(shmid,IPC_RMID,&buf)
107
108del_sem(semid)
109
110return 0
111
112}
113
114
115
116
117
118
119
120
121
欢迎分享,转载请注明来源:夏雨云
评论列表(0条)