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