libASSA Programmer's Manual | ||
---|---|---|
<<< Previous | Chapter 4. Class Reference | Next >>> |
Fork class is a simple wrapper around C library function fork(). Main advantage of using Fork over fork() is that child termination process is handled internally by the static destructor of Fork.
class Fork { public: enum state_t { KILL_ON_EXIT, WAIT_ON_EXIT, LEAVE_ALONE }; Fork (state_t s_ = WAIT_ON_EXIT); ~Fork (); bool isParent() const; bool isChild() const; pid_t getChildPID() const; }; |
Forking is done by instantiation Fork object. For example:
void Client:: initServer () { // peform some initialization Fork ss (Fork::KILL_ON_EXIT); // Fork and exec server-side. if (ss.isChild ()) { execlp ("bufio_tests", "bufio_tests", "-p", getPortName().c_str(), "-D", "~/log/bufioSdb", NULL); /*--- unreachable ---*/ cerr << "error: " << "bufio_tests" << ": "; cerr << "exec(3) failed: " << strerror (errno)); } else if (ss.isParent ()) { m_child_pid = ss.getChildPID (); cout << "Child PID " << m_child_pid << endl; sleep (2); // Give the server chance to run } } |
Each Fork object has a state. By default, the state assigned is Fork::WAIT_ON_EXIT. Here are all possible states that Fork object can take:
Fork::WAIT_ON_EXIT - Parent process will wait until child exits.
Fork::KILL_ON_EXIT - Parent process will kill the child with SIGTERM on exit.
Fork::LEAVE_ALONE - Parent process will do nothing at all, possibly leaving zombie process behind.
Fork doesn't provide the exit status of the child process. If you need to examine the exit status, you have to explicitly wait for the status with ::wait(2).
When Fork is used in GenServer application, GenServer sets up SIGCHLD's disposition to SIG_IGN with the following side effect:
" If process sets SIGCHLD's disposition to SIG_IGN, child processes will not create zombie processes when they terminate (see exit(2)). If the parent process subsequently waits for its children to exit, it blocks until they are all terminated; it then returns -1 with errno set to ECHILD (see wait(2) and waitid(2)). "
For further example, please see $src/tests/fork_test.cpp. Fork class is used extensively by other test programs as well.
<<< Previous | Home | Next >>> |
CmdLineOpts class | Up | IdSet Class |