-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathipc_util.cpp
138 lines (115 loc) · 2.42 KB
/
ipc_util.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
#include "ipc_util.h"
namespace MY_IPC
{
// 所有自定义异常
SEM_EXCEPTION sem_exception;
SHM_EXCEPTION shm_exception;
int create_sem(const char * path, int id, int sem_num, int val=1)
{
key_t ipc_key;
int sem_id;
union semun tmp;
ipc_key = ftok(path, id);
if (ipc_key == -1)
{
sem_exception.set("ftok fail");
throw sem_exception;
}
sem_id = semget(ipc_key, sem_num, IPC_CREAT | 0666); //所有用户进程可读可写
if (sem_id == -1)
{
sem_exception.set("create shared Memory error");
throw sem_exception;
}
// 批量设置信号量初始值
tmp.val = val;
for (int i = 0; i < sem_num; i++)
{
if (semctl(sem_id, i, SETVAL, tmp) == -1)
{
sem_exception.set("semctl set val error");
throw sem_exception;
}
}
return sem_id;
}
void sem_wait(int sid, int sn){
struct sembuf op;
op.sem_num=sn;
op.sem_op=-1;
op.sem_flg=0;
if(semop(sid, &op, 1)==-1){
sem_exception.set("sem_wait fail");
throw sem_exception;
}
}
void sem_signal(int sid, int sn)
{
struct sembuf op;
op.sem_num = sn;
op.sem_op = 1;
op.sem_flg = 0;
if (semop(sid, &op, 1) == -1)
{
sem_exception.set("sem_signal fail");
throw sem_exception;
}
}
void remove_sem(int sid)
{
if (semctl(sid, 0, IPC_RMID) == -1)
{
sem_exception.set("clear sem fail");
throw sem_exception;
}
}
int create_shm(const char *path, int id, size_t shmsize)
{
int shm_id;
char *shm;
key_t ipc_key = ftok(path, id);
if (ipc_key == -1)
{
sem_exception.set("create ipc_key fail");
throw sem_exception;
}
if ((shm_id = shmget(ipc_key, shmsize, IPC_CREAT | 0666)) == -1)//所有用户进程可读可写
{
sem_exception.set("Create shm Error");
throw sem_exception;
}
shm = (char*)connect_shm(shm_id);
shm[0] = '\0';
cut_shm((const void *)shm);
return shm_id;
}
void * connect_shm(int shm_id)
{
void *p;
char *q;
p = shmat(shm_id, NULL, 0); // shmat 第二个参数设为NULL,即让系统自动选择地址映射,第三个参数是标志,一般为0
q = (char*)p;
if ((long)q == -1)
{
shm_exception.set("connet shm fail");
throw shm_exception;
}
return p;
}
void * cut_shm(const void * addr)
{
if (shmdt(addr) == -1)
{
shm_exception.set("cut shm relation fail");
throw shm_exception;
}
}
void remove_shm(int shm_id)
{
if (shmctl(shm_id, IPC_RMID, NULL) == -1)
{
shm_exception.set("shmctl IPC_RMID Error");
throw shm_exception;
}
}
}// MY_IPC