//=========================================================================
// Summary  : */
// Filename : SharedObjectServerNonblocking.cc
// Author   : */
// Project  : */
// Revision : 1
// Created  : 2000/08/19
// Modified : 2000/08/19
//=========================================================================
// Description :
//=========================================================================
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/name.h>
#include <sys/kernel.h>
#include <sys/psinfo.h>
#include "SharedObjectServerNonblocking.h"

#include "MyAssert.h"
#include "Syslog.h"
#include "utils/System.h"

SharedObjectServerNonblocking::SharedObjectServerNonblocking(const char *name)
  : SharedObjectServer(name)
{
}


SharedObjectServerNonblocking::~SharedObjectServerNonblocking()
{
  Boolean debug = False;
  
  dprintf("SharedObjectServer::~SharedObjectServer()");

  if (_processNameId != -1) {
    qnx_name_detach(0, _processNameId);
    dprintf("SharedObjectServer::~SharedObjectServer() - detached name");
  }

  dprintf("SharedObjectServer::~SharedObjectServer() - free()...");
  free((void *)_requestPtr);
  dprintf("SharedObjectServer::~SharedObjectServer() - done");
}



void SharedObjectServerNonblocking::run()
{
  allocateBuffers();

  Boolean debug = False;

  int nReplyBytes;
  Reply *replyPtr;

  // Launch callbacks (note this is pure virtual, and should actually
  // call the most-inherited function
  init();

  while (True) {
    // Give the other processes a chance to do something.
    System::milliSleep(1);

    // Try to get a message without blocking
    _clientPid = Creceive(AnyPid, (void *)_requestPtr, _maxReqBytes);

    // Did we find a message?
    if (_clientPid == -1)
    {
      // No message pending.  Call OnIdle();
      onIdle();
    }
    else if (_clientPid)
    {
      dprintf("SharedObjectServer::run() - received message, code %d\n",
	      _requestPtr->code);

      // Call appropriate method
      if (processRequest(_requestPtr, _maxReqBytes, &replyPtr, &nReplyBytes)) 
      {
        // Reply to client
        dprintf("SharedObjectServer::run() - Reply to client %d with %d bytes\n",
	        _clientPid, nReplyBytes);

        Reply(_clientPid, (void *)replyPtr, nReplyBytes);
        dprintf("SharedObjectServer::run() - done with Reply()\n");
      }
    }
  }
}

void SharedObjectServerNonblocking::onIdle()
{
  Assert(false /*SharedObjectServerNonblocking::onIdle called*/);
}
