forked from bd-group/dservice
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdevmap.c
More file actions
97 lines (83 loc) · 1.89 KB
/
devmap.c
File metadata and controls
97 lines (83 loc) · 1.89 KB
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
/**
* Copyright (c) 2012 IIE, all rights reserved.
*
* Ma Can <ml.macana@gmail.com> OR <macan@iie.ac.cn>
*
* Armed with EMACS.
* Time-stamp: <2013-12-20 20:39:49 macan>
*
*/
#include <unistd.h>
#include "common.h"
#include "devmap_DevMap.h"
static int g_valid = 0;
static int open_shm()
{
int fd = 0, oflag = O_RDONLY;
fd = shm_open(DEV_MAPPING, oflag, 0644);
if (fd < 0) {
printf("shm_open(%s) failed w/ %s\n", DEV_MAPPING, strerror(errno));
return -1;
}
return fd;
}
#define SHMLOCK_UN 0
#define SHMLOCK_WR 1
#define SHMLOCK_RD 2
static int lock_shm(int fd, int type)
{
struct flock lock;
int err = 0;
switch (type) {
case SHMLOCK_UN:
lock.l_type = F_UNLCK;
break;
case SHMLOCK_WR:
lock.l_type = F_WRLCK;
break;
case SHMLOCK_RD:
lock.l_type = F_RDLCK;
break;
}
lock.l_start = 0;
lock.l_whence = SEEK_SET;
lock.l_len = 0;
lock.l_pid = getpid();
err = fcntl(fd, F_SETLKW, &lock);
if (err) {
printf("lock shm file failed w/ %s\n", strerror(errno));
}
return err;
}
static void close_shm(int fd)
{
close(fd);
}
JNIEXPORT jboolean JNICALL Java_devmap_DevMap_isValid(JNIEnv *env, jclass cls)
{
return g_valid;
}
JNIEXPORT jstring JNICALL Java_devmap_DevMap_getDevMaps(JNIEnv *env, jclass cls)
{
jstring content;
char *res = "";
char buf[4096];
int err = 0;
/* Step 1: open the shm */
int fd = open_shm();
if (fd < 0) {
goto out;
}
/* Step 2: read in the content */
memset(buf, 0, sizeof(buf));
lock_shm(fd, SHMLOCK_RD);
err = read(fd, buf, 4096);
lock_shm(fd, SHMLOCK_UN);
if (err < 0)
printf("read in shm file error %s(%d)\n", strerror(errno), errno);
close_shm(fd);
res = buf;
out:
content = (*env)->NewStringUTF(env, res);
return content;
}