// =====================================================================
//  $Id: TOutputObjectSharedMemory.cc,v 1.1.1.1 2003/06/27 02:56:41 goiwai Exp $
//  $Name: CLDAQ-1-06-02 $
// =====================================================================
#include "TOutputObjectSharedMemory.hh"
#include "TStreamableObject.hh"
#include "TObjectFilter.hh"
#include "TRunManager.hh"
#include "TUserInterface.hh"

TOutputObjectSharedMemory::TOutputObjectSharedMemory( Tint memsize, Tint maxevt )
  : TObjectSharedMemory( memsize, maxevt ),
    TOutputObjectStream( tSharedMemoryStream )
{
  signal( SIGINT, TOutputObjectSharedMemory::catchSignal );
  signal( SIGSEGV, TOutputObjectSharedMemory::catchSignal );
}

TOutputObjectSharedMemory::TOutputObjectSharedMemory( TObjectFilter* filter, Tint memsize, Tint maxevt )
  : TObjectSharedMemory( memsize, maxevt ),
    TOutputObjectStream( filter, tSharedMemoryStream )
{
  signal( SIGINT, TOutputObjectSharedMemory::catchSignal );
  signal( SIGSEGV, TOutputObjectSharedMemory::catchSignal );
}

TOutputObjectSharedMemory::~TOutputObjectSharedMemory()
{
  Detach();
  Remove();
}

Tint TOutputObjectSharedMemory::Write( TStreamableObject& object )
{
  SetReadable( Tfalse );

  theLastDataSize = theDataSize;
  theDataSize = 0;

  if ( theCurrentPositionOfMemorySpace == theMaxEvent - 1 ) {
    // return to top
    theAddress = theBaseAddress;
    theCurrentPositionOfMemorySpace = 0;
  }
    
  if ( HasFilter() ) {
    theDataSize = theObjectFilter -> Filtering( object, this );
  } else {
    theDataSize = object.Record( this );
  }

  if ( theDataSize > 0 ) {
    theCurrentPositionOfMemorySpace ++;
  }

  //( (Tchar*)theAddress ) += theDataSize;

  SetReadable( Ttrue );
  theTotalDataSize += theDataSize;
  return( theDataSize );
}

Tvoid TOutputObjectSharedMemory::catchSignal( Tint sigid )
{
  Tstring head = "TOutputObjectSharedMemory::catchSignal: ";
  Tcout << head << "get signal " << sigid << "." << Tendl;
  Tcout << head << "detach/remove IPC resources." << Tendl;
  TObjectSharedMemory::GetObjectSharedMemory() -> Detach();
  TObjectSharedMemory::GetObjectSharedMemory() -> Remove();

  TRunManager* manager = TRunManager::GetRunManager();
  if ( manager ) {
    Tcout << head << "terminate RunManager by force." << Tendl;
    manager -> GetUserInterface() -> ExecuteCommand( "exit" );
    delete manager;
  }

  exit( errno );
}
