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