1 /*
2 * Copyright (c) 2022-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 "sandbox_utils.h"
17 #include <cstdlib>
18 #include <cstring>
19
20 #ifdef _WIN32
21 #include <windows.h>
22 #endif
23
24 namespace OHOS {
25 #if !defined(OHOS_LITE) && !defined(_WIN32) && !defined(__APPLE__) && !defined(__gnu_linux__)
26 const int PID_STR_SIZE = 4;
27 const int STATUS_LINE_SIZE = 1024;
28
FindAndConvertPid(char * buf)29 static int FindAndConvertPid(char *buf)
30 {
31 int count = 0;
32 char pidBuf[11] = {0}; /* 11: 32 bits to the maximum length of a string */
33 char *str = buf;
34 while (*str != '\0') {
35 if ((*str >= '0') && (*str <= '9')) {
36 pidBuf[count] = *str;
37 count++;
38 str++;
39 continue;
40 }
41
42 if (count > 0) {
43 break;
44 }
45 str++;
46 }
47 return atoi(pidBuf);
48 }
49 #endif
50
GetRealPid(void)51 pid_t GetRealPid(void)
52 {
53 #ifdef _WIN32
54 return GetCurrentProcessId();
55 #elif defined(OHOS_LITE) || defined(__APPLE__) || defined(__gnu_linux__)
56 return getpid();
57 #else
58 const char *path = "/proc/self/status";
59 char buf[STATUS_LINE_SIZE] = {0};
60 FILE *fp = fopen(path, "r");
61 if (fp == nullptr) {
62 return -1;
63 }
64
65 while (!feof(fp)) {
66 if (fgets(buf, STATUS_LINE_SIZE, fp) == nullptr) {
67 fclose(fp);
68 return -1;
69 }
70 if (strncmp(buf, "Pid:", PID_STR_SIZE) == 0) {
71 break;
72 }
73 }
74 (void)fclose(fp);
75
76 return static_cast<pid_t>(FindAndConvertPid(buf));
77 #endif
78 }
79 } // namespace OHOS
80