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 <unistd.h>
17
18 #include "os/error.h"
19 #include "os/failure_retry.h"
20 #include "sys/wait.h"
21 #include "utils/expected.h"
22 #include "utils/span.h"
23
24 namespace panda::os::exec {
25
Exec(Span<const char * > args)26 Expected<int, Error> Exec(Span<const char *> args)
27 {
28 ASSERT(!args.Empty());
29 ASSERT(args[args.Size() - 1] == nullptr && "Last argument must be a nullptr");
30
31 pid_t pid = fork();
32 if (pid == 0) {
33 setpgid(0, 0);
34 execv(args[0], const_cast<char **>(args.Data()));
35 _exit(1);
36 }
37
38 if (pid < 0) {
39 return Unexpected(Error(errno));
40 }
41 int status = -1;
42 pid_t res_pid = PANDA_FAILURE_RETRY(waitpid(pid, &status, 0));
43 if (res_pid != pid) {
44 return Unexpected(Error(errno));
45 }
46 if (WIFEXITED(status)) { // NOLINT(hicpp-signed-bitwise)
47 return WEXITSTATUS(status); // NOLINT(hicpp-signed-bitwise)
48 }
49 return Unexpected(Error("Process finished improperly"));
50 }
51
52 } // namespace panda::os::exec
53