Add RunFunc to Subprocess for just executing function
[platform/core/appfw/app-installers.git] / src / common / utils / subprocess.h
1 // Copyright (c) 2015 Samsung Electronics Co., Ltd All Rights Reserved
2 // Use of this source code is governed by an apache-2.0 license that can be
3 // found in the LICENSE file.
4
5 #ifndef COMMON_UTILS_SUBPROCESS_H_
6 #define COMMON_UTILS_SUBPROCESS_H_
7
8 #include <string>
9 #include <utility>
10 #include <vector>
11 #include <functional>
12 #include <unistd.h>
13
14 namespace common_installer {
15
16 class Subprocess {
17  public:
18   explicit Subprocess(const std::string& program);
19
20   template<typename ...Args> bool Run(Args&&... args) {
21     std::vector<std::string> argv{std::forward<Args>(args)...};
22     return RunWithArgs(argv);
23   }
24
25   template <typename... Args>
26   bool RunFunc(std::function<int(Args...)> func, Args&&... args) {
27     if (started_) {
28       return false;
29     }
30     pid_ = fork();
31     if (pid_ == 0) {
32       exit(func(std::forward<Args>(args)...));
33       return false;
34     } else if (pid_ == -1) {
35       return false;
36     } else {
37       started_ = true;
38       return true;
39     }
40   }
41
42   bool RunWithArgs(
43       const std::vector<std::string>& args = std::vector<std::string>());
44   int Wait();
45
46   void set_uid(int uid) {
47     uid_ = uid;
48   }
49
50   void Kill();
51
52  private:
53   std::string program_;
54   int pid_;
55   bool started_;
56   int uid_;
57 };
58
59 }  // namespace common_installer
60
61 #endif  // COMMON_UTILS_SUBPROCESS_H_