1 /*
2 * Copyright (c) 2021-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 <unistd.h>
17 #include "libpandabase/os/exec.h"
18 #include "libpandabase/os/failure_retry.h"
19 #include "sys/wait.h"
20
21 namespace ark::os::exec {
22
ExecNoWait(Span<const char * > args)23 Expected<int, Error> ExecNoWait(Span<const char *> args)
24 {
25 ASSERT(!args.Empty());
26 ASSERT_PRINT(args[args.Size() - 1] == nullptr, "Last argument must be a nullptr");
27
28 if (pid_t pid = fork(); pid == 0) {
29 setpgid(0, 0);
30 execv(args[0], const_cast<char **>(args.Data()));
31 _exit(1);
32 } else if (pid < 0) {
33 return Unexpected(Error(errno));
34 } else {
35 return pid;
36 }
37 }
38
Wait(int64_t process,bool testStatus)39 Expected<int, Error> Wait(int64_t process, bool testStatus)
40 {
41 auto pid = static_cast<pid_t>(process);
42 ASSERT(pid == process);
43
44 int status = -1;
45 pid_t resPid = PANDA_FAILURE_RETRY(waitpid(pid, &status, 0));
46 if (resPid != pid) {
47 return Unexpected(Error(errno));
48 }
49
50 if (!testStatus) {
51 return status;
52 }
53
54 if (WIFEXITED(status)) { // NOLINT(hicpp-signed-bitwise)
55 return WEXITSTATUS(status); // NOLINT(hicpp-signed-bitwise)
56 }
57 return Unexpected(Error("Process finished improperly"));
58 }
59
Exec(Span<const char * > args)60 Expected<int, Error> Exec(Span<const char *> args)
61 {
62 auto res = ExecNoWait(args);
63 if (!res.HasValue()) {
64 return res;
65 }
66 pid_t pid = res.Value();
67 return Wait(pid, true);
68 }
69
70 } // namespace ark::os::exec
71