1 /*
2 * Copyright (c) 2021-2022 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 "run_shell_util.h"
17 #include <cstdio>
18 #include "define_multimodal.h"
19
20 namespace OHOS {
21 namespace MMI {
22 namespace {
23 const std::string HILOG_GREP = "hilog -x | grep ";
24 constexpr int32_t MAXSIZE = 1000;
25 const std::regex REGEX_LOG("\n");
26 static inline constexpr OHOS::HiviewDFX::HiLogLabel LABEL = { LOG_CORE, MMI_LOG_DOMAIN, "RUNSHELLUTILL" };
27 }
28
RunShellUtil()29 RunShellUtil::RunShellUtil(): logMaxSize_(100) {}
30
~RunShellUtil()31 RunShellUtil::~RunShellUtil() {}
32
RunShellCommand(const std::string & command,std::vector<std::string> & vLog)33 int32_t RunShellUtil::RunShellCommand(const std::string &command, std::vector<std::string> &vLog)
34 {
35 MMI_LOGD("enter");
36 vLog.clear();
37 const std::string command_ = HILOG_GREP + "'" + command + "'";
38
39 if ((fp_ = popen(command_.c_str(), "r")) == nullptr) {
40 MMI_LOGE("open fail");
41 return RET_ERR;
42 }
43 std::string retLog = "";
44 int32_t i = 0;
45 while (logMaxSize_ > i) {
46 char buf[MAXSIZE] = {0};
47 if (fgets(buf, sizeof(buf), fp_) == nullptr) {
48 MMI_LOGE("read fp end");
49 retLog.append(std::string(buf));
50 pclose(fp_);
51 fp_ = nullptr;
52 break;
53 }
54 retLog.append(std::string(buf));
55 i++;
56 }
57 if (retLog.length() == 0) {
58 MMI_LOGD("retLog is empty");
59 return RET_OK;
60 }
61 StringToVectorByRegex(retLog, vLog, REGEX_LOG);
62 return RET_OK;
63 }
64
SetLogMaxSize(int32_t logSize)65 int32_t RunShellUtil::SetLogMaxSize(int32_t logSize)
66 {
67 if (logSize <= 0) {
68 return RET_ERR;
69 }
70 logMaxSize_ = logSize;
71 return RET_OK;
72 }
73
StringToVectorByRegex(const std::string & log,std::vector<std::string> & vLog,const std::regex & r)74 int32_t RunShellUtil::StringToVectorByRegex(const std::string &log, std::vector<std::string> &vLog, const std::regex &r)
75 {
76 std::vector<std::string> v(std::sregex_token_iterator(log.begin(), log.end(), r, -1),
77 std::sregex_token_iterator());
78 vLog = v;
79 return RET_OK;
80 }
81 } // namespace MMI
82 } // namespace OHOS
83