//=========================================================================
// Summary  : */
// Filename : Fork.cc
// Author   : */
// Project  : */
// Revision : 1
// Created  : 2001/01/22
// Modified : 2001/01/22
//=========================================================================
// Description :
//=========================================================================

#include "Fork.h"

#include "Exception.h"
#include "Syslog.h"
#include <stdlib.h>
#include "MyAssert.h"
#include <unistd.h>
#include <iostream.h>



//#include "remote/Remote.h"


//#include "remote/RemoteBrokerTask.h"
//#include "remote/Broker.h"
//#include "remote/ModemController.h"
//#include "remote/ModemIFQNX.h"
//#include "ModemMessage.h"
//#include "remote/ModemSerial.h"
//#include "remote/ModemSocket.h"


extern int fork();

Fork::Fork()
{
  _bSuccess = false;
  _bRunCalled = false;
  _pidParent = 0;
  _pidChild = 0;
}

Fork::~Fork()
{
}

void Fork::run()
{
  // Perform fork.
  _bRunCalled = true;
  int iFork = fork();

  // Were we successful?
  if (iFork == -1)
  {
    // No!  Error!
    Assert(false);
    throw Exception("Fork failed");
  }
  else
  {
    // Fork successful!!

    // iFork is zero if we have a child, and the pid of the child if we have a parent.
    if (iFork)
//        if (!iFork)  // reverse parent and thread for debugging!
    {
      // We are the parent.
      _bIsParent = true;
      _pidParent = getpid();
      _pidChild  = iFork;
      _bSuccess  = true;

      VerifyParent();

      printf("PARENT\n");
      cerr << "PARENT\n";
      cout << "PARENT\n";

      runParent();
    }
    else
    {
      // We are the children.
      _bIsParent = false;
      _pidParent = getppid();
      _pidChild  = getpid();
      _bSuccess  = true;

      VerifyChild();

      printf("CHILD\n");
      cerr << "CHILD\n";
      cout << "CHILD\n";

      runChild();
    }
  }  
}


void Fork::runParent()
{
  VerifyParent();
}

void Fork::runChild()
{
  VerifyChild();
}
