1 /*
2 * Copyright (C) 2017 The Android Open Source Project
3 *
4 * Licensed under the Apache License, Version 2.0 (the "License");
5 * you may not use this file except in compliance with the License.
6 * You may obtain a copy of the License at
7 *
8 * http://www.apache.org/licenses/LICENSE-2.0
9 *
10 * Unless required by applicable law or agreed to in writing, software
11 * distributed under the License is distributed on an "AS IS" BASIS,
12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 * See the License for the specific language governing permissions and
14 * limitations under the License.
15 */
16
17 #define LOG_TAG "hidl_test_servers"
18
19 #include "hidl_test.h"
20
21 #include <android-base/logging.h>
22
23 #include <android/hardware/tests/baz/1.0/IBaz.h>
24
25 #include <hidl/LegacySupport.h>
26
27 #include <hwbinder/IPCThreadState.h>
28
29 #include <sys/wait.h>
30 #include <signal.h>
31
32 #include <string>
33 #include <utility>
34 #include <vector>
35
36 using ::android::hardware::tests::baz::V1_0::IBaz;
37
38 using ::android::hardware::defaultPassthroughServiceImplementation;
39 using ::android::hardware::IPCThreadState;
40
41 static std::vector<std::pair<std::string, pid_t>> gPidList;
42
signal_handler_server(int signal)43 void signal_handler_server(int signal) {
44 if (signal == SIGTERM) {
45 IPCThreadState::shutdown();
46 exit(0);
47 }
48 }
49
50 template <class T>
51 struct ForkServer {
runForkServer52 static void run(const std::string& serviceName) {
53 pid_t pid;
54
55 if ((pid = fork()) == 0) {
56 // in child process
57 signal(SIGTERM, signal_handler_server);
58 int status = defaultPassthroughServiceImplementation<T>(serviceName);
59 exit(status);
60 }
61
62 gPidList.push_back({serviceName, pid});
63 }
64 };
65
killServer(pid_t pid,const char * serverName)66 static void killServer(pid_t pid, const char *serverName) {
67 if (kill(pid, SIGTERM)) {
68 ALOGE("Could not kill %s; errno = %d", serverName, errno);
69 } else {
70 int status;
71 ALOGE("Waiting for %s to exit...", serverName);
72 waitpid(pid, &status, 0);
73 if (status != 0) {
74 ALOGE("%s terminates abnormally with status %d", serverName, status);
75 } else {
76 ALOGE("%s killed successfully", serverName);
77 }
78 ALOGE("Continuing...");
79 }
80 }
81
signal_handler(int signal)82 void signal_handler(int signal) {
83 if (signal == SIGTERM) {
84 for (const auto& p : gPidList) {
85 killServer(p.second, p.first.c_str());
86 }
87 exit(0);
88 }
89 }
90
main(int,char * [])91 int main(int /* argc */, char* /* argv */ []) {
92 android::hardware::details::setTrebleTestingOverride(true);
93
94 runOnEachServer<ForkServer>();
95
96 ForkServer<IBaz>::run("dyingBaz");
97
98 signal(SIGTERM, signal_handler);
99 // Parent process should not exit before the forked child processes.
100 pause();
101
102 return 0;
103 }
104