RAUL  0.5.1
Process.hpp
1 /* This file is part of Raul.
2  * Copyright (C) 2007 Dave Robillard <http://drobilla.net>
3  *
4  * Raul is free software; you can redistribute it and/or modify it under the
5  * terms of the GNU General Public License as published by the Free Software
6  * Foundation; either version 2 of the License, or (at your option) any later
7  * version.
8  *
9  * Raul is distributed in the hope that it will be useful, but WITHOUT ANY
10  * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
11  * FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
12  *
13  * You should have received a copy of the GNU General Public License along
14  * with this program; if not, write to the Free Software Foundation, Inc.,
15  * 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
16  */
17 
18 #ifndef RAUL_PROCESS_HPP
19 #define RAUL_PROCESS_HPP
20 
21 #include <string>
22 #include <iostream>
23 #include <unistd.h>
24 #include <sys/time.h>
25 #include <sys/resource.h>
26 #include <boost/utility.hpp>
27 
28 namespace Raul {
29 
30 
35 class Process : boost::noncopyable
36 {
37 public:
38 
43  static bool launch(const std::string& command) {
44  const std::string executable = (command.find(" ") != std::string::npos)
45  ? command.substr(0, command.find(" "))
46  : command;
47 
48  const std::string arguments = command.substr((command.find(" ") + 1));
49 
50  std::cerr << "Launching child process '" << executable << "' with arguments '"
51  << arguments << "'" << std::endl;
52 
53  // Use the same double fork() trick as JACK to prevent zombie children
54  const int err = fork();
55 
56  if (err == 0) {
57  // (child)
58 
59  // close all nonstandard file descriptors
60  struct rlimit max_fds;
61  getrlimit(RLIMIT_NOFILE, &max_fds);
62 
63  for (rlim_t fd = 3; fd < max_fds.rlim_cur; ++fd)
64  close(fd);
65 
66  switch (fork()) {
67  case 0:
68  // (grandchild)
69  setsid();
70  execlp(executable.c_str(), arguments.c_str(), NULL);
71  _exit(-1);
72 
73  case -1:
74  // (second) fork failed, there is no grandchild
75  _exit (-1);
76 
77  /* exit the child process here */
78  default:
79  _exit (0);
80  }
81  }
82 
83  return (err > 0);
84  }
85 
86 private:
87  Process() {}
88 };
89 
90 
91 } // namespace Raul
92 
93 #endif // RAUL_PROCESS_HPP
static bool launch(const std::string &command)
Launch a sub process.
Definition: Process.hpp:43
Definition: Array.hpp:26
A child process.
Definition: Process.hpp:35