| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
You can effectively use the Fork wrapper class to create child
processes. You can use the Fork class, instead of directly using the
system call fork (), if you desire the following:
In what follows,
killchild is an integer.
reason is an integer.
signo is a valid signal.
f is a Fork object.
Fork f(killchild, reason)
Fork object f. The constructor creates a child
process. When the parent process terminates, it will kill the child
process if killchild is not 0. Otherwise, the parent process will
wait until all its child processes die. If reason is not 0, then
it gives the reason for a child process's death on the stderr.
f.is_child ()
Fork object f. Otherwise, return 0.
f.is_parent ()
Fork object f. Otherwise, return 0.
f.process_id ()
Fork::suicide_signal (signo)
signo, the current process will kill all its child processes
created through Fork::Fork(int, int) irrespective of the value of
the killchild flag used in the construction of the Fork
objects. signo defaults to SIGTERM signal.
| [ < ] | [ > ] | [ << ] | [ Up ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |
The following example illustrates the use of the Fork class to
create child processes. First, we set up SIGTERM signal handler
to kill all the child processes, by callling Fork::suicide_signal
(). Second, we create several child and grandchild processes.
You can kill the top most parent process and all its children by sending a SIGTERM signal to the top most parent process.
// tfork.C
#include <iostream.h>
#include <Fork.h>
static void print (char* name, pid_t child)
{
if (child)
cerr << "Parent " << getppid () << "; "
<< name << ' ' << getpid () << "; Child " << child << ";\n";
}
int main (int ac, char** av)
{
Fork::suicide_signal (SIGTERM);
Fork a(0, 1);
print ("a", a.process_id ());
if (a.is_child ()) {
sleep (3000);
} else if (a.is_parent ()) {
Fork b (1, 1);
print ("b", b.process_id ());
{
Fork c (b.is_parent (), 1);
if (b.is_child ())
print ("cchild", c.process_id ());
else
print ("cparent", c.process_id ());
if (c.is_child ()) {
sleep (3000);
return 0;
}
}
if (b.is_child ()) {
sleep (120);
return 0x8;
}
}
return 0;
}
|
| [ << ] | [ >> ] | [Top] | [Contents] | [Index] | [ ? ] |