1 /* 2 * Copyright (c) 2025 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 <unistd.h> 17 #include <cstdio> 18 #include <sys/stat.h> 19 #include <fcntl.h> 20 #include <iostream> 21 #include <getopt.h> 22 #include <mutex> 23 #include <condition_variable> 24 #include "ipc_transactor.h" 25 #include "api_caller_client.h" 26 #include "api_caller_server.h" 27 #include "frontend_api_handler.h" 28 29 using namespace std; 30 31 namespace OHOS::perftest { TranslateToken(string_view raw)32 static string TranslateToken(string_view raw) 33 { 34 if (raw.find_first_of('@') != string_view::npos) { 35 return string(raw); 36 } 37 return "default"; 38 } 39 StartDaemon(string_view token)40 static int32_t StartDaemon(string_view token) 41 { 42 if (token.empty()) { 43 LOG_E("Empty transaction token"); 44 return EXIT_FAILURE; 45 } 46 auto transalatedToken = TranslateToken(token); 47 if (daemon(0, 0) != 0) { 48 LOG_E("Failed to daemonize current process"); 49 return EXIT_FAILURE; 50 } 51 LOG_I("Server starting up"); 52 ApiCallerServer apiCallerServer; 53 auto &apiServer = FrontendApiServer::Get(); 54 auto apiHandler = std::bind(&FrontendApiServer::Call, &apiServer, placeholders::_1, placeholders::_2); 55 auto cbHandler = std::bind(&ApiCallerServer::Transact, &apiCallerServer, placeholders::_1, placeholders::_2); 56 apiServer.SetCallbackHandler(cbHandler); // used for callback from server to client 57 if (!apiCallerServer.InitAndConnectPeer(transalatedToken, apiHandler)) { 58 LOG_E("Failed to initialize server"); 59 _Exit(0); 60 return EXIT_FAILURE; 61 } 62 mutex mtx; 63 unique_lock<mutex> lock(mtx); 64 condition_variable condVar; 65 apiCallerServer.SetDeathCallback([&condVar]() { 66 condVar.notify_one(); 67 }); 68 LOG_I("PerfTest-daemon running, pid=%{public}d", getpid()); 69 condVar.wait(lock); 70 LOG_I("Server exit"); 71 apiCallerServer.Finalize(); 72 _Exit(0); 73 return 0; 74 } 75 main(int32_t argc,char * argv[])76 extern "C" int32_t main(int32_t argc, char *argv[]) 77 { 78 LOG_I("Server command start"); 79 if ((size_t)argc < THREE) { 80 _Exit(EXIT_FAILURE); 81 } 82 string command(argv[INDEX_ONE]); 83 if (command == "start-daemon") { 84 string_view token = argv[INDEX_TWO]; 85 _Exit(StartDaemon(token)); 86 } 87 _Exit(EXIT_FAILURE); 88 } 89 } // namespace OHOS::perftest