0b48479da7fcb217eb3f09b77c3dc0e3b04ef02f
[iec.git] / src / type3_AndroidCloud / anbox-master / external / process-cpp-minimal / src / core / posix / exec.cpp
1 /*
2  * Copyright © 2013 Canonical Ltd.
3  *
4  * This program is free software: you can redistribute it and/or modify it
5  * under the terms of the GNU Lesser General Public License version 3,
6  * as published by the Free Software Foundation.
7  *
8  * This program is distributed in the hope that it will be useful,
9  * but WITHOUT ANY WARRANTY; without even the implied warranty of
10  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
11  * GNU Lesser General Public License for more details.
12  *
13  * You should have received a copy of the GNU Lesser General Public License
14  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
15  *
16  * Authored by: Thomas Voß <thomas.voss@canonical.com>
17  */
18
19 #include <core/posix/exec.h>
20 #include <core/posix/fork.h>
21 #include <core/posix/standard_stream.h>
22
23 #include <iostream>
24
25 #include <cstring>
26
27 #include <unistd.h>
28
29 namespace core
30 {
31 namespace posix
32 {
33 ChildProcess exec(const std::string& fn,
34                   const std::vector<std::string>& argv,
35                   const std::map<std::string, std::string>& env,
36                   const StandardStream& flags)
37 {
38     std::function<void()> null_function = [](){};
39     return exec(fn, argv, env, flags, null_function);
40 }
41
42 ChildProcess exec(const std::string& fn,
43                   const std::vector<std::string>& argv,
44                   const std::map<std::string, std::string>& env,
45                   const StandardStream& flags,
46                   const std::function<void()>& child_setup)
47 {
48     return posix::fork([fn, argv, env, child_setup]()
49     {
50         char** it; char** pargv; char** penv;
51         it = pargv = new char*[argv.size()+2];
52         *it = ::strdup(fn.c_str());
53         it++;
54         for (auto element : argv)
55         {
56             *it = ::strdup(element.c_str());
57             it++;
58         }
59         *it = nullptr;
60
61         it = penv = new char*[env.size()+1];
62         for (auto pair : env)
63         {
64             *it = ::strdup((pair.first + "=" + pair.second).c_str());
65             it++;
66         }
67         *it = nullptr;
68
69         child_setup();
70         return static_cast<posix::exit::Status>(execve(fn.c_str(), pargv, penv));
71     }, flags);
72 }
73
74 }
75 }