wibble  1.1
childprocess.h
Go to the documentation of this file.
1 // -*- C++ -*-
2 
3 #ifndef WIBBLE_SYS_CHILDPROCESS_H
4 #define WIBBLE_SYS_CHILDPROCESS_H
5 
6 /*
7  * OO base class for process functions and child processes
8  *
9  * Copyright (C) 2003--2006 Enrico Zini <enrico@debian.org>
10  *
11  * This library is free software; you can redistribute it and/or
12  * modify it under the terms of the GNU Lesser General Public
13  * License as published by the Free Software Foundation; either
14  * version 2.1 of the License, or (at your option) any later version.
15  *
16  * This library is distributed in the hope that it will be useful,
17  * but WITHOUT ANY WARRANTY; without even the implied warranty of
18  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
19  * Lesser General Public License for more details.
20  *
21  * You should have received a copy of the GNU Lesser General Public
22  * License along with this library; if not, write to the Free Software
23  * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24  */
25 
26 #include <sys/types.h>
27 #include <wibble/exception.h>
28 #include <wibble/sys/macros.h>
29 
30 #ifdef _WIN32
31 #include <windows.h>
32 #endif
33 
34 struct rusage;
35 
36 namespace wibble {
37 namespace sys {
38 
43 {
44 protected:
45  pid_t _pid;
46  int pipes[3][2];
47 
49  int m_status;
50  bool m_doExec;
51  std::string m_command;
52 
53 #ifdef _WIN32
54  int backups[3];
55  STARTUPINFO si;
56  PROCESS_INFORMATION pi;
57 #endif
58 
62  // TODO: since the destructor is called twice (one in the parent and one in
63  // the child), it could be useful to add a bool isChild() method to let the
64  // destructor and other functions know where they are operating. The value
65  // returned can be set by ChildProcess::fork.
66 
67  virtual int main() = 0;
68 
79  virtual void spawnChild();
80 
81  void waitError();
82  void setupPipes();
83  void setupPrefork();
84  void setupChild();
85  void setupParent();
86 
87 public:
88  ChildProcess() : _pid(-1), _stdin( 0 ), _stdout( 0 ), _stderr( 0 ) {}
89  virtual ~ChildProcess() {}
90 
94  void setExec( std::string command ) {
95  m_doExec = true;
96  m_command = command;
97  }
98 
103  pid_t fork();
104 
105  void setupRedirects(int* stdinfd = 0, int* stdoutfd = 0, int* stderrfd = 0);
106 
107  pid_t forkAndRedirect(int* stdinfd = 0, int* stdoutfd = 0, int* stderrfd = 0) {
108  setupRedirects(stdinfd, stdoutfd, stderrfd);
109  return fork();
110  }
111 
119  pid_t pid() const { return _pid; }
120 
121  bool running();
122  int exitStatus();
123  void waitForSuccess();
124 
128  int wait(struct rusage* ru = 0);
129 
131  void kill(int signal);
132 };
133 
134 }
135 }
136 
137 // vim:set ts=4 sw=4:
138 #endif