[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

10. Fork Class

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,

Fork f(killchild, reason)
constructs a 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 ()
returns 1 if the current process is the child process following the fork in constructing the Fork object f. Otherwise, return 0.

f.is_parent ()
returns 1 if the current process is the parent process following the fork in constructing the Fork object f. Otherwise, return 0.

f.process_id ()
returns the process id of the child process, if the current process is the parent process. Returns 0, if the current process is the child process. Returns -1, if fork failed.

Fork::suicide_signal (signo)
is a static function. Upon the reciept of the signal 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] [ ? ]

10.1 Fork Example

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] [ ? ]

This document was generated by Herbert Straub on June, 15 2005 using texi2html