1 /*
2  * Copyright (c) 2024 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 "dlp_fuse_fd.h"
17 
18 #include <pthread.h>
19 #include <unistd.h>
20 #include "dlp_permission_log.h"
21 #ifdef LOG_TAG
22 #undef LOG_TAG
23 #define LOG_TAG "DlFuseFd"
24 #endif
25 
26 static int g_dlpFuseFd = -1;
27 static pthread_mutex_t g_mutex = PTHREAD_MUTEX_INITIALIZER;
28 
GetDlpFuseFd(void)29 int GetDlpFuseFd(void)
30 {
31     pthread_mutex_lock(&g_mutex);
32     if (g_dlpFuseFd == -1) {
33         DLP_LOG_ERROR("Fuse fd not set!");
34     }
35     DLP_LOG_DEBUG("fuseFd: %d\n", g_dlpFuseFd);
36     pthread_mutex_unlock(&g_mutex);
37     return g_dlpFuseFd;
38 }
39 
SetDlpFuseFd(int fd)40 void SetDlpFuseFd(int fd)
41 {
42     pthread_mutex_lock(&g_mutex);
43     if (g_dlpFuseFd != -1) {
44         DLP_LOG_DEBUG("close fuseFd: %d first\n", g_dlpFuseFd);
45         close(g_dlpFuseFd);
46     }
47     g_dlpFuseFd = fd;
48     DLP_LOG_DEBUG("fuseFd: %d\n", g_dlpFuseFd);
49     pthread_mutex_unlock(&g_mutex);
50 }
51 
CloseDlpFuseFd(void)52 void CloseDlpFuseFd(void)
53 {
54     pthread_mutex_lock(&g_mutex);
55     if (g_dlpFuseFd == -1) {
56         DLP_LOG_DEBUG("fuseFd: %d\n", g_dlpFuseFd);
57         pthread_mutex_unlock(&g_mutex);
58         return;
59     }
60     close(g_dlpFuseFd);
61     g_dlpFuseFd = -1;
62     pthread_mutex_unlock(&g_mutex);
63 }
64