Apache Mesos
exec.hpp
Go to the documentation of this file.
1 // Licensed under the Apache License, Version 2.0 (the "License");
2 // you may not use this file except in compliance with the License.
3 // You may obtain a copy of the License at
4 //
5 // http://www.apache.org/licenses/LICENSE-2.0
6 //
7 // Unless required by applicable law or agreed to in writing, software
8 // distributed under the License is distributed on an "AS IS" BASIS,
9 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
10 // See the License for the specific language governing permissions and
11 // limitations under the License.
12 
13 #ifndef __STOUT_OS_POSIX_EXEC_HPP__
14 #define __STOUT_OS_POSIX_EXEC_HPP__
15 
16 #include <stdlib.h> // For exit.
17 #include <unistd.h> // For fork, exec*.
18 
19 #include <sys/wait.h> // For waitpid.
20 
21 #include <string>
22 #include <vector>
23 
24 #include <stout/none.hpp>
25 #include <stout/option.hpp>
26 
27 #include <stout/os/raw/argv.hpp>
29 
30 namespace os {
31 
33  const std::string& file,
34  const std::vector<std::string>& arguments)
35 {
36  pid_t pid = ::fork();
37 
38  if (pid == -1) {
39  return None();
40  } else if (pid == 0) {
41  // In child process.
42  ::execvp(file.c_str(), os::raw::Argv(arguments));
43  ::exit(127);
44  } else {
45  // In parent process.
46  int status;
47  while (::waitpid(pid, &status, 0) == -1) {
48  if (errno != EINTR) {
49  return None();
50  }
51  }
52 
53  return status;
54  }
55 }
56 
57 
58 inline int execvp(const char* file, char* const argv[])
59 {
60  return ::execvp(file, argv);
61 }
62 
63 
64 inline int execvpe(const char* file, char** argv, char** envp)
65 {
66  char** saved = os::raw::environment();
67 
68  *os::raw::environmentp() = envp;
69 
70  int result = execvp(file, argv);
71 
72  *os::raw::environmentp() = saved;
73 
74  return result;
75 }
76 
77 } // namespace os {
78 
79 #endif // __STOUT_OS_POSIX_EXEC_HPP__
Result< ProcessStatus > status(pid_t pid)
Definition: proc.hpp:166
int execvp(const std::string &file, const std::vector< std::string > &argv)
Definition: exec.hpp:442
Definition: posix_signalhandler.hpp:23
char *** environmentp()
Definition: environment.hpp:88
int execvp(const char *file, char *const argv[])
Definition: exec.hpp:58
Represent the argument list expected by execv routines.
Definition: argv.hpp:36
DWORD pid_t
Definition: windows.hpp:181
URI file(const std::string &path)
Creates a file URI with the given path on the local host.
Definition: file.hpp:33
Result< pid_t > waitpid(pid_t pid, int *status, int options)
Definition: os.hpp:141
Definition: none.hpp:27
int execvpe(const char *file, char **argv, char **envp)
Definition: exec.hpp:64
Option< int > spawn(const std::string &file, const std::vector< std::string > &arguments)
Definition: exec.hpp:32
char ** environment()
Definition: environment.hpp:66