1 /*
2 * Copyright (c) 2021 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 "os/exec.h"
17
18 #include <cstring>
19 #include <unistd.h>
20 #include "os/unix/failure_retry.h"
21 #include "sys/wait.h"
22
23 namespace panda::os::exec {
24
Exec(Span<const char * > args)25 Expected<int, Error> Exec(Span<const char *> args)
26 {
27 ASSERT(!args.Empty());
28 ASSERT(args[args.Size() - 1] == nullptr && "The last argument must be nullptr");
29
30 pid_t pid = fork();
31 if (pid == 0) {
32 setpgid(0, 0);
33 execv(args[0], const_cast<char **>(args.Data()));
34 _exit(1);
35 }
36
37 if (pid < 0) {
38 return Unexpected(Error(errno));
39 }
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