SPH
Process.cpp
Go to the documentation of this file.
1 #include "system/Process.h"
2 #include "io/FileSystem.h"
3 #include <sys/types.h>
4 #include <sys/wait.h>
5 
7 
8 class ProcessException : public std::exception {
9 private:
10  std::string message;
11 
12 public:
13  ProcessException(const std::string& message)
14  : message(message) {}
15 
16  virtual const char* what() const noexcept override {
17  return message.c_str();
18  }
19 };
20 
22  if (!FileSystem::pathExists(path)) {
23  throw ProcessException("Path " + path.native() + " does not exist");
24  }
25  pid_t pid = fork();
26  if (pid == -1) {
27  throw ProcessException("Process fork failed");
28  } else if (pid == 0) {
29  // child process
30  Array<char*> argv;
31  std::string fileName = path.native();
33  argv.push(const_cast<char*>(fileName.c_str()));
34  for (std::string& arg : args) {
35  argv.push(const_cast<char*>(arg.c_str()));
36  }
37  argv.push(nullptr);
38 
39  execvp(fileName.c_str(), &argv[0]);
40 
41  // execl replaces the current process with a new one, so we should never get past the call
42  throw ProcessException("Cannot execute file " + fileName);
43  } else {
44  SPH_ASSERT(pid > 0);
45  // parent process, save the child pid
46  childPid = pid;
47  }
48 }
49 
50 void Process::wait() {
51  int status;
52  pid_t pid;
53  do {
54  pid = waitpid(childPid, &status, 0);
55  } while (pid != childPid && status != -1);
56 }
57 
#define SPH_ASSERT(x,...)
Definition: Assert.h:94
NAMESPACE_SPH_BEGIN
Definition: BarnesHut.cpp:13
#define NAMESPACE_SPH_END
Definition: Object.h:12
Creating and managing processes.
INLINE void push(U &&u)
Adds new element to the end of the array, resizing the array if necessary.
Definition: Array.h:306
Object representing a path on a filesystem.
Definition: Path.h:17
std::string native() const
Returns the native version of the path.
Definition: Path.cpp:71
virtual const char * what() const noexcept override
Definition: Process.cpp:16
ProcessException(const std::string &message)
Definition: Process.cpp:13
void wait()
Blocks the calling thread until the managed process exits. The function may block indefinitely.
Definition: Process.cpp:50
Process()=default
Creates a null process handle.
bool pathExists(const Path &path)
Checks if a file or directory exists (or more precisely, if a file or directory is accessible).
Definition: FileSystem.cpp:21