process-cpp  1.0.0
A simple convenience library for handling processes in C++11.
exec.cpp
Go to the documentation of this file.
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>
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  return posix::fork([fn, argv, env]()
39  {
40  char** it; char** pargv; char** penv;
41  it = pargv = new char*[argv.size()+2];
42  *it = ::strdup(fn.c_str());
43  it++;
44  for (auto element : argv)
45  {
46  *it = ::strdup(element.c_str());
47  it++;
48  }
49  *it = nullptr;
50 
51  it = penv = new char*[env.size()+1];
52  for (auto pair : env)
53  {
54  *it = ::strdup((pair.first + "=" + pair.second).c_str());
55  it++;
56  }
57  *it = nullptr;
58 
59  return static_cast<posix::exit::Status>(execve(fn.c_str(), pargv, penv));
60  }, flags);
61 }
62 }
63 }
Status
The Status enum wrap's the posix exit status.
Definition: exit.h:33
StandardStream
The StandardStream enum wraps the POSIX standard streams.
CORE_POSIX_DLL_PUBLIC ChildProcess fork(const std::function< posix::exit::Status()> &main, const StandardStream &flags)
fork forks a new process and executes the provided main function in the newly forked process...
Definition: fork.cpp:57
CORE_POSIX_DLL_PUBLIC ChildProcess exec(const std::string &fn, const std::vector< std::string > &argv, const std::map< std::string, std::string > &env, const StandardStream &flags)
exec execve's the executable with the provided arguments and environment.
Definition: exec.cpp:33
The Process class models a child process of this process.
Definition: child_process.h:43