1 /*
2  * Copyright (c) 2023 Huawei Device Co., Ltd.
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  *     http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12  * See the License for the specific language governing permissions and
13  * limitations under the License.
14  */
15 
16 #include <cstdio>
17 #include <ctime>
18 #include <fcntl.h>
19 #include <js_native_api.h>
20 #include <js_native_api_types.h>
21 #include <node_api.h>
22 #include <semaphore.h>
23 #include <unistd.h>
24 
25 #define MPARAM_1 (-1)
26 #define PARAM_1 1
27 #define PARAM_0 0
28 #define PARAM_0777 0777
29 
SemUnlink(napi_env env, napi_callback_info info)30 static napi_value SemUnlink(napi_env env, napi_callback_info info)
31 {
32     char buf[100];
33     struct timespec ts;
34     int ret = MPARAM_1;
35     sem_t *psem = SEM_FAILED;
36     do {
37         clock_gettime(CLOCK_REALTIME, &ts);
38         snprintf(buf, sizeof(buf), "/testsem-%d-%d", static_cast<int>(getpid()), static_cast<int>(ts.tv_nsec));
39         psem = sem_open(buf, O_CREAT, PARAM_0777, PARAM_1);
40         if (psem == SEM_FAILED) {
41             break;
42         }
43         ret = sem_close(psem);
44         if (ret == MPARAM_1) {
45             break;
46         }
47         ret = sem_unlink(buf);
48     } while (PARAM_0);
49     napi_value result = nullptr;
50     napi_create_int32(env, ret, &result);
51     return result;
52 }
53 
54 EXTERN_C_START
Init(napi_env env, napi_value exports)55 static napi_value Init(napi_env env, napi_value exports)
56 {
57     napi_property_descriptor desc[] = {
58         {"sem_unlink", nullptr, SemUnlink, nullptr, nullptr, nullptr, napi_default, nullptr},
59     };
60     napi_define_properties(env, exports, sizeof(desc) / sizeof(desc[0]), desc);
61     return exports;
62 }
63 
64 EXTERN_C_END
65 
66 static napi_module demoModule = {
67     .nm_version = 1,
68     .nm_flags = 0,
69     .nm_filename = nullptr,
70     .nm_register_func = Init,
71     .nm_modname = "semaphore1",
72     .nm_priv = ((void *)0),
73     .reserved = {0},
74 };
75 
RegisterEntryModule(void)76 extern "C" __attribute__((constructor)) void RegisterEntryModule(void) { napi_module_register(&demoModule); }
77