-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathChildProcess.h
More file actions
81 lines (65 loc) · 2.54 KB
/
ChildProcess.h
File metadata and controls
81 lines (65 loc) · 2.54 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/**
* This file has the definition for the ChildProcess
* class. This class provides a convenient API to fork and execute
* other programs.
*/
#include <string>
#include <vector>
#ifndef CHILD_PROCESS_H
#define CHILD_PROCESS_H
// A convenience shortcut to a vector-of-strings
using StrVec = std::vector<std::string>;
/**
* A simple class to help with forking & executing programs in a child
* process. This class maintains the PID of the child process in an
* instance variable.
*/
class ChildProcess {
public:
/** A simple default (no-argument) constructor. This constructor
merely initializes (so the body of the method should be
empty!) the childPid instance variable to -1.
*/
ChildProcess();
/** The destructor. This method cleans-up any resources (like open
files etc.). However, this class is very simple and the
destructor is just an empty method.
Note: Destructor for an object is called when the object goes
out of scope.
*/
~ChildProcess();
/** The primary method in this class that:
1. First uses the fork system call to create a child process.
2. In the child process it calls myExec to execute a program.
3. In the parent process, it stores the value in childPid and
returns the childPid value.
\param[in] argList The list of command-line arguments. The
first entry is assumed to be the command to be executed.
\return This method returns the pid value of the child process
forked by this method.
*/
int forkNexec(const StrVec& argList);
/** Helper method to wait for child process to finish. This
method calls the waitpid system call. It obtains the exit code
of the child process from the 2nd argument of the waitpid
system call.
\return This method returns the exit code of the child
process.
*/
int wait() const;
protected:
/** A helper method to setup pointers and call execvp system call.
This method should be called from a child process. Don't call
this method directly. Instead, call the forkNexec API method.
\param[in] argList The list of command-line arguments. The
first entry is assumed to be the command to be executed.
*/
void myExec(StrVec argList);
private:
/** The only instance variable in this class. It is initialized
to -1 in the constructor. The value is changed by the
forkNexec method.
*/
int childPid;
};
#endif