-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmodule_hello.c
More file actions
68 lines (58 loc) · 2.1 KB
/
module_hello.c
File metadata and controls
68 lines (58 loc) · 2.1 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
#include "quickjs.h"
#include <stdlib.h>
#include "quickjs-libc.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#define countof(x) (sizeof(x) / sizeof((x)[0]))
static JSValue js_memory(JSContext *ctx, JSValueConst this_val,
int argc, JSValueConst *argv)
{
FILE *file = fopen("/proc/meminfo", "r");
if (file == NULL) {
perror("Error opening meminfo file");
return JS_EXCEPTION;
}
char line[256];
long totalMemoryValue = -1; // Initialize with an error value
while (fgets(line, sizeof(line), file)) {
if (strncmp(line, "MemTotal", 8) == 0) {
char *ptr = line + 9; // Move pointer past "MemTotal:"
while (*ptr == ' ') ptr++; // Skip spaces
char *endptr;
totalMemoryValue = strtol(ptr, &endptr, 10);
if (ptr == endptr) {
fprintf(stderr, "Error: No digits were found in MemTotal value\n");
totalMemoryValue = -1;
} else if (totalMemoryValue == LONG_MIN || totalMemoryValue == LONG_MAX) {
fprintf(stderr, "Error: MemTotal value is out of range\n");
totalMemoryValue = -1;
}
break; // Stop after reading MemTotal
}
}
fclose(file);
if (totalMemoryValue == -1) {
return JS_ThrowInternalError(ctx, "Failed to read MemTotal from /proc/meminfo");
}
return JS_NewInt64(ctx, totalMemoryValue);
}
static const JSCFunctionListEntry js_test_funcs[] = {
JS_CFUNC_DEF("memory", 1, js_memory ),
};
static int js_test_init(JSContext *ctx, JSModuleDef *m){
return JS_SetModuleExportList(ctx, m, js_test_funcs,
countof(js_test_funcs));
}
JSModuleDef *js_init_module_test(JSContext *ctx, const char *module_name)
{
JSModuleDef *m;
// 创建一个模块,包含这个模块有多少方法或者变量
m = JS_NewCModule(ctx, module_name, js_test_init);
if (!m)
return NULL;
// 注册这个模块到 quickjs 的运行时。
JS_AddModuleExportList(ctx, m, js_test_funcs, countof(js_test_funcs));
return m;
}