Example #1
0
//! [Window constructor start]
Window::Window()
{
    thread = new RenderThread();
//! [Window constructor start] //! [set up widgets and connections]

    label = new QLabel();
    label->setAlignment(Qt::AlignCenter);

    loadButton = new QPushButton(tr("&Load image..."));
    resetButton = new QPushButton(tr("&Stop"));
    resetButton->setEnabled(false);

    connect(loadButton, SIGNAL(clicked()), this, SLOT(loadImage()));
    connect(resetButton, SIGNAL(clicked()), thread, SLOT(stopProcess()));
    connect(thread, SIGNAL(finished()), this, SLOT(resetUi()));
//! [set up widgets and connections] //! [connecting signal with custom type]
    connect(thread, SIGNAL(sendBlock(Block)), this, SLOT(addBlock(Block)));
//! [connecting signal with custom type]

    QHBoxLayout *buttonLayout = new QHBoxLayout();
    buttonLayout->addStretch();
    buttonLayout->addWidget(loadButton);
    buttonLayout->addWidget(resetButton);
    buttonLayout->addStretch();

    QVBoxLayout *layout = new QVBoxLayout(this);
    layout->addWidget(label);
    layout->addLayout(buttonLayout);

//! [Window constructor finish]
    setWindowTitle(tr("Queued Custom Type"));
}
Example #2
0
void WinDbgThread::startProcess(const QString& filename)
{
    stopProcess();
    m_bOwnsProcess = true;
    m_processFileName = filename;
    m_pi.dwProcessId = 0;
    QThread::start();
}
Example #3
0
//! 
void ArgManager::analyse(int argc, char *argv[])
{
	// Lecture des paramétres
	int nbParam = (argc-1)/2;
	int acParam = 0;
	while(acParam <= nbParam && nbParam>0)
	{
		acParam++;
		string argTag = string(argv[acParam]);	
		absArgument* arg = getArg(argTag);
		if(arg==NULL){
			cerr << "Erreur argument " << argTag << " : tag non valide" << endl;
			stopProcess();
		}
		
		Argument<string>* strArg = dynamic_cast<Argument<string>* >(arg);
		Argument<int>* intArg = dynamic_cast<Argument<int>* >(arg);
		if(strArg)
		{	
			cerr << "if(strArg) ok" << " Value = " << string(argv[acParam+1]);
			strArg->validArg();
			strArg->setValue(string(argv[++acParam]));
		}
		else if(intArg)
		{
			// cerr << "acParam = " << acParam << "argc = "<< argc << endl;
			// cerr << "if(intArg) ok" << " Value = " << string(argv[acParam+1]) << endl;
			intArg->validArg();
			string strInt = string(argv[++acParam]);
			intArg->setValue(atoi(strInt.c_str()));
		}
		else
		{
			cerr << "Erreur argument " << argTag << " : type non valide" << endl;
			stopProcess();
		}

	}
}
Example #4
0
bool PCProcess::setMemoryAccessRights(Address start, size_t size,
                                      PCMemPerm rights) {
    // if (PAGE_EXECUTE_READWRITE == rights || PAGE_READWRITE == rights) {
    if (rights.isRWX() || rights.isRW() ) {
        mapped_object *obj = findObject(start);
        int page_size = getMemoryPageSize();
        for (Address cur = start; cur < (start + size); cur += page_size) {
            obj->removeProtectedPage(start -(start % page_size));
        }
    }
    stopProcess();
    changeMemoryProtections(start, size, rights, true);
	return true;
}
Example #5
0
bool ProcessServer::stopProcess( dword processId )
{
	AutoLock lock( &m_Lock );

	if ( m_ProcessInfo.find( processId ).valid() )
	{
		ProcessInfo & info = m_ProcessInfo[ processId ];

		Event stopProcess( CharString().format("StopProcess%u", ::Process::getProcessId( info.m_pHandle )) );
		stopProcess.signal();

		return true;
	}

	return false;
}
/**
* Receives a packet and tries to write the packet into the ringbuffer
*/
void PCAPExporterMem::receive(Packet* packet)
{
    DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive() called");
    if (onRestart) {
        DPRINTF("Dropping incoming packet, as attached process is not ready");
        DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive() ended");
        packet->removeReference();
        return;
    }
    if (fifoReaderPid == 0) {
        msg(MSG_VDEBUG, "fifoReaderPid = 0...this might happen during reconfiguration");
        DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive() ended");
        packet->removeReference();
        return;
    }
    if (restartInterval) {
        if (nextRestart.tv_sec==0) {
            DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive(): updating nextRestart");
            nextRestart = packet->timestamp;
            nextRestart.tv_sec += restartInterval;
        } else if (compareTime(nextRestart, packet->timestamp)<0) {
            DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive(): restarting process");

            // we need to unregister our signal handlers, as we get race conditions with the signal handler for restarting the process
            unregisterSignalHandlers();
            stopProcess();
            startProcess();
            registerSignalHandlers();
            DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive(): updating nextRestart");
            nextRestart.tv_sec += ((packet->timestamp.tv_sec-nextRestart.tv_sec)/restartInterval+1)*restartInterval;
        }
    }

    if (writeIntoMemory(packet)) {
        statPktsForwarded++;
        statBytesForwarded += packet->data_length;
        DPRINTFL(MSG_VDEBUG, "Wrote packet at pos %u", *nextWrite);
    } else {
        batchUpdate();

        statPktsDropped++;
        statBytesDropped += packet->data_length;
        DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive(): dropped packet");
    }
    packet->removeReference();
    DPRINTFL(MSG_VDEBUG, "PCAPExporterMem::receive() ended");
}
  void MOPACInputDialog::computeClicked()
  {
    if (m_process != 0) {
      QMessageBox::warning(this, tr("MOPAC Running."),
                           tr("MOPAC is already running. Wait until the previous calculation is finished."));
      return;
    }

    QString fileName = saveInputFile(ui.previewText->toPlainText(), tr("MOPAC Input Deck"), QString("mop"));
    if (fileName.isEmpty())
      return;

    QFileInfo info(mopacPath);
    if (!info.exists() || !info.isExecutable()) {
      QMessageBox::warning(this, tr("MOPAC Not Installed."),
                           tr("The MOPAC executable, cannot be found."));
      return;
    }

    m_process = new QProcess(this);
    QFileInfo input(fileName);
    m_process->setWorkingDirectory(input.absolutePath());

    QStringList arguments;
    arguments << fileName;
    m_inputFile = fileName; // save for reading in output

    m_process->start(mopacPath, arguments);
    if (!m_process->waitForStarted()) {
      QMessageBox::warning(this, tr("MOPAC failed to start."),
                           tr("MOPAC did not start. Perhaps it is not installed correctly."));
    }
    connect(m_process, SIGNAL(finished(int)), this, SLOT(finished(int)));
    m_progress = new QProgressDialog(this);
    m_progress->setRange(0,0); // indeterminate progress
    m_progress->setLabelText(tr("Running MOPAC calculation..."));
    m_progress->show();
    connect(m_progress, SIGNAL(canceled()), this, SLOT(stopProcess()));
  }
Example #8
0
//=====================================
// Stop processes and release all data
//=====================================
void cJulius::release( void )
{

	if ( ! m_recog ) return;

	stopProcess();

	if (m_threadHandle) {
		CloseHandle(m_threadHandle);
		m_threadHandle = NULL;
	} else {
		if ( m_recog ) {
			j_recog_free( m_recog );  // jconf will be released inside this
			m_recog = NULL;
			m_jconf = NULL;
		}
		if ( m_jconf ) {
			j_jconf_free( m_jconf );
			m_jconf = NULL;
		}
	}

}
Example #9
0
/**
 * @brief VLC module destruct callback
 * @param obj
 */
static void y4m_close(vlc_object_t* obj)
{
    filter_t* intf = (filter_t*)obj;
    filter_sys_t* sys = intf->p_sys;

    msg_Info(intf, "close");

    // process stop causes thread exit if blocked on write
    stopProcess(intf);

    // cancel causes thread exit if blocked in mutex or cond wait
    if (sys->inputThread.handle)
    {
        vlc_cancel(sys->inputThread);
        vlc_join(sys->inputThread, NULL);
    }

    // output should be dead if input is
    if (sys->outputThread.handle)
        vlc_join(sys->outputThread, NULL);

    picture_fifo_Flush(sys->inputFifo, LAST_MDATE, true);
    picture_fifo_Flush(sys->outputFifo, LAST_MDATE, true);

    picture_fifo_Delete(sys->inputFifo);
    picture_fifo_Delete(sys->outputFifo);

    vlc_cond_destroy(&sys->inputCond);
    vlc_cond_destroy(&sys->outputCond);

    vlc_mutex_destroy(&sys->inputMutex);
    vlc_mutex_destroy(&sys->outputMutex);

    free(sys->cmd);
    free(sys);
}
Example #10
0
WinDbgThread::~WinDbgThread()
{
    stopProcess();
}
Example #11
0
void ProcessServer::onReceive( dword client, byte message, const InStream & input )
{
	//LOG_STATUS( "ProcessServer","onReceive, client = %u (%s), message = 0x%x", client, clientAddress(client), message );

	switch( message )
	{
	case ProcessClient::SERVER_LOGIN:
		{
			dword job;
			input >> job;
			CharString uid;
			input >> uid;
			CharString md5;
			input >> md5;

			bool result = false;

			MetaClient::Profile profile;
			if ( m_MetaClient.loginByProxy( uid, md5, profile ) > 0 )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Login %s, client %u (%s)", profile.name.cstr(), client, clientAddress(client)) );
				result = (profile.flags & (MetaClient::ADMINISTRATOR|MetaClient::SERVER)) != 0;
			}
			else
				LOG_STATUS( "ProcessServer", CharString().format("Login failed, client %u (%s)", client, clientAddress(client)) );

			AutoLock lock( &m_Lock );

			m_ClientValid[ client ] = result;
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << result;
		}
		break;
	case ProcessClient::SERVER_SESSION_LOGIN:
		{
			dword job;
			input >> job;
			dword sessionId;
			input >> sessionId;

			bool result = false;

			MetaClient::Profile profile;
			if ( m_MetaClient.loginByProxy( sessionId, profile ) > 0 )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Login %s, client %u (%s)", profile.name.cstr(), client, clientAddress(client)) );
				result = (profile.flags & MetaClient::ADMINISTRATOR) != 0;
			}
			else
				LOG_STATUS( "ProcessServer", CharString().format("Login failed, client %u (%s)", client, clientAddress(client)) );

			AutoLock lock( &m_Lock );

			m_ClientValid[ client ] = result;
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << result;
		}
		break;
	case ProcessClient::SERVER_SEND_PROCESS_LIST:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			// send process list to the server
			AutoLock lock( &m_Lock );
			send( client, ProcessClient::CLIENT_RECV_PROCESS_LIST ) << job << m_ProcessList;
		}
		break;
	case ProcessClient::SERVER_SEND_CONFIG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString config;
			CharString configFile;

			if ( processId != 0 )
			{
				Process proc;
				if ( findProcess( processId, proc ) )
					configFile = proc.config;
			}
			else
				configFile = m_Context.config;

			LOG_STATUS( "ProcessServer", CharString().format("Send Config, client %u (%s), configFile = %s", 
				client, clientAddress(client), configFile.cstr()) );

			// attempt to load the configuration file
			char * pConfig = FileDisk::loadTextFile( configFile );
			if ( pConfig != NULL )
			{
				config = pConfig;
				delete [] pConfig;
			}

			send( client, ProcessClient::CLIENT_RECV_CONFIG ) << job << config;
		}
		break;
	case ProcessClient::SERVER_RECV_CONFIG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;
			CharString config;
			input >> config;

			bool jobDone = false;

			CharString configFile;
			if ( processId != 0 )
			{
				Process proc;
				if ( findProcess( processId, proc ) )
					configFile = proc.config;
			}
			else
				configFile = m_Context.config;

			LOG_STATUS( "ProcessServer", "Recv Config, client %u (%s), configFile = %s", 
				client, clientAddress(client), configFile.cstr() );

			// save the new file
			jobDone = FileDisk::saveTextFile( configFile, CharString( config ) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_SEND_LOG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString log;
			CharString logFile;
			if ( processId != 0 )
			{
				// send log of one of our processes
				Process proc;
				if ( findProcess( processId, proc ) )
					logFile = proc.log;
			}
			else
				logFile = m_Context.logFile;

			FileDisk file;
			if ( file.open( logFile ) )
			{
				dword size = file.size();
				if ( size > MAX_LOG_SIZE )
				{
					file.setPosition( size - MAX_LOG_SIZE );
					size = MAX_LOG_SIZE;
				}

				char * pLog = new char[ size + 1];
				pLog[ size ] = 0;

				file.read( pLog, size );
				file.close();

				// save to string
				log = pLog;
				// release allocated memory
				delete [] pLog;
			}
			else
				log = "Failed to open log file!";


			send( client, ProcessClient::CLIENT_RECV_LOG ) << job << log;
		}
		break;
	case ProcessClient::SERVER_ADD_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			Process proc;
			input >> proc;

			AutoLock lock( &m_Lock );

			proc.processId = m_NextProcessId++;
			m_ProcessList.push( proc );

			LOG_STATUS( "ProcessServer", "Add Process, client = %u (%s), processId = %u, name = %s, exec = %s", 
				client, clientAddress(client), proc.processId, proc.name.cstr(), proc.executable.cstr() );

			saveProcessList();
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << true;
		}
		break;
	case ProcessClient::SERVER_SET_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			Process proc;
			input >> proc;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( proc.processId );
			if ( pi >= 0 )
			{
				m_ProcessList[pi] = proc;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Set Process, client = %u (%s), processId = %u, name = %s, exec = %s", 
					client, clientAddress(client), proc.processId, proc.name.cstr(), proc.executable.cstr() );

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_DEL_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				LOG_STATUS( "ProcessServer", "Delete Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );

				// stop the actual process if any
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					::Process::stop( m_ProcessInfo[ processId ].m_pHandle );
					m_ProcessInfo.remove( processId );
				}

				// remove from the list
				m_ProcessList.remove( pi );
				jobDone = true;

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_STOP_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				m_ProcessList[ pi ].flags |= ProcessClient::PF_DISABLED;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Stop Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );

				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_START_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			int pi = findProcess( processId );
			if ( pi >= 0 )
			{
				m_ProcessList[ pi ].flags &= ~ProcessClient::PF_DISABLED;
				jobDone = true;

				LOG_STATUS( "ProcessServer", "Start Process, name = %s, client = %u (%s), processId = %u", 
					m_ProcessList[pi].name.cstr(), client, clientAddress(client), processId );
				saveProcessList();
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_RESTART_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			Process proc;
			if ( findProcess( processId, proc ) )
			{
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					jobDone = stopProcess( processId );

					LOG_STATUS( "ProcessServer", "Restart Process, name = %s, client = %u (%s), processId = %u,", 
						proc.name.cstr(), client, clientAddress(client), processId );
				}
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_SEND_STATUS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			AutoLock lock( &m_Lock );

			ProcessClient::Status status;
			status.processGroup = m_Context.processGroup;
			status.networkGroup = m_Context.networkGroup;
			status.cpuUsage = cpuUsage();
			status.memoryUsage = memoryUsage();	
			status.processCount = 0;

			for(int i=0;i<m_ProcessList.size();i++)
				if ( (m_ProcessList[i].flags & ProcessClient::PF_RUNNING) != 0 )
					status.processCount++;

			send( client, ProcessClient::CLIENT_RECV_STATUS ) << job << status;
		}
		break;
	case ProcessClient::SERVER_STOP_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				m_ProcessList[i].flags |= ProcessClient::PF_DISABLED;
			saveProcessList();

			jobDone = true;

			LOG_STATUS( "ProcessServer", CharString().format("Stop All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_START_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				m_ProcessList[i].flags &= ~ProcessClient::PF_DISABLED;
			saveProcessList();

			jobDone = true;
			LOG_STATUS( "ProcessServer", CharString().format("Start All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_RESTART_ALL:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = false;

			AutoLock lock( &m_Lock );
			for(int i=0;i<m_ProcessList.size();i++)
				stopProcess( m_ProcessList[i].processId );

			jobDone = true;
			LOG_STATUS( "ProcessServer", CharString().format("Restart All, client = %u (%s)", client, clientAddress(client)) );
			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_REBOOT:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			bool jobDone = reboot();
			if ( jobDone )
				LOG_STATUS( "ProcessServer", CharString().format("Server Rebooting, client = %u (%s)", client, clientAddress(client)) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_EXIT:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;

			// signal all running processes to stop
			bool jobDone = shutdown();
			if ( jobDone )
				LOG_STATUS( "ProcessServer", CharString().format("Server Exiting, client = %u (%s)", client, clientAddress(client)) );

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_TERMINATE_PROCESS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			bool jobDone = false;

			AutoLock lock( &m_Lock );

			Process proc;
			if ( findProcess( processId, proc ) )
			{
				// just terminate the process
				if ( m_ProcessInfo.find( processId ).valid() )
				{
					::Process::stop( m_ProcessInfo[ processId ].m_pHandle );
					jobDone = true;

					LOG_STATUS( "ProcessServer", "Terminated Process, name = %s, client = %u (%s), processId = %u,", 
						proc.name.cstr(), client, clientAddress(client), processId );
				}
			}

			send( client, ProcessClient::CLIENT_JOB_DONE ) << job << jobDone;
		}
		break;
	case ProcessClient::SERVER_OPEN_LOG:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			dword processId;
			input >> processId;

			CharString logFile;
			if ( processId != 0 )
			{
				// send log of one of our processes
				Process proc;
				if ( findProcess( processId, proc ) )
					logFile = proc.log;
			}
			else
				logFile = m_Context.logFile;

			dword logId = m_NextLogId++;

			AutoLock lock( &m_Lock );

			FileDisk & file = m_LogFile[ logId ];
			if ( file.open( logFile ) )
			{
				LOG_STATUS( "ProcessServer", "Open Log, logFile = %s, logId = %u, clientId = %u", logFile.cstr(), logId, client );

				m_ActiveLog.push( logId );
				m_LogClient[ logId ] = client;
				m_ClientLog[ client ].push( logId );
			}
			else
			{
				LOG_STATUS( "ProcessServer", "Open Log Failed, logFile = %s, clientId = %u", logFile.cstr(), client );

				// failed to open file
				m_LogFile.remove( logId );
				// set id to 0 for error
				logId = 0;
			}

			send( client, ProcessClient::CLIENT_RECV_LOG_ID ) << job << logId;
		}
		break;
	case ProcessClient::SERVER_CLOSE_LOG:
		if ( validateClient( client ) )
		{
			dword logId;
			input >> logId;

			AutoLock lock( &m_Lock );

			LOG_STATUS( "ProcessServer", CharString().format("Close Log, logId = %u, client = %u", logId, client) );

			m_ActiveLog.removeSearch( logId );
			m_LogFile.remove( logId );
			m_LogClient.remove( logId );
			m_ClientLog[ client ].removeSearch( logId );
		}
		break;
	case ProcessClient::SERVER_SEARCH_LOGS:
		if ( validateClient( client ) )
		{
			dword job;
			input >> job;
			ProcessClient::SearchLogRequest req;
			input >> req;

			LOG_STATUS( "ProcessServer", CharString().format("Search Log, clientId = %u", client) );

			CharString result;
			if( req.filemask.find('/') >= 0 || req.filemask.find('\\') >= 0 )
			{	// this should never happen, unless the user has a hacked client
				LOG_STATUS( "ProcessServer", CharString().format("Search Log, invalid filemask received from clientId = %u", client) );
				result = "Failed";
			}
			else
			{
				result = searchLogFiles( req.filemask, req.searchString, req.isRegExp, req.searchLevel, req.resolveClientId );
			}

			send( client, ProcessClient::CLIENT_RECV_SEARCHRESULT ) << job << result;
		}
		break;
	case ProcessClient::PING:
		send( client, ProcessClient::PONG );
		break;
	case ProcessClient::PONG:
		break;
	default:
		{
			LOG_ERROR( "ProcessServer", CharString().format("Bad Message, client = %u (%s), message = %d", client, clientAddress(client), message) );
			removeClient( client );
		}
		break;
	}
}
Example #12
0
/**
 * Writes a packet into the pipe
 */
void PCAPExporterPipe::receive(Packet* packet)
{
	DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() called");
	if (onRestart){
		 DPRINTF("Dropping incoming packet, as attached process is not ready");
		 DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() ended");
		 packet->removeReference();
		 return;
	}
	if (fifoReaderPid == 0){
		 msg(MSG_VDEBUG, "fifoReaderPid = 0...this might happen during reconfiguration");
		 DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() ended");
		 packet->removeReference();
		 return;
	}
	if (restartInterval) {
		if (nextRestart.tv_sec==0) {
			DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive(): updating nextRestart");
			nextRestart = packet->timestamp;
			struct timeval tv = { restartInterval/1000, (restartInterval % 1000)*1000 };
			timeval_add(&nextRestart, &tv);
		} else if (compareTime(nextRestart, packet->timestamp)<0) {
			DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive(): restarting process");

			// we need to unregister our signal handlers, as we get race conditions with the signal handler for restarting the process
			unregisterSignalHandlers();
			stopProcess();
			startProcess();
			registerSignalHandlers();
			DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive(): updating nextRestart");
			timeval tvdiff;
			timeval_subtract(&tvdiff, &packet->timestamp, &nextRestart);
			uint32_t msdiff = tvdiff.tv_sec*1000+tvdiff.tv_usec/1000;
			uint32_t mswait = (msdiff/restartInterval+1)*restartInterval;
			tvdiff.tv_sec = mswait/1000;
			tvdiff.tv_usec = (mswait%1000)*1000;
			timeval_add(&nextRestart, &tvdiff);
		}
	}

	// write packet
	static struct pcap_pkthdr packetHeader;
	packetHeader.ts = packet->timestamp;
	packetHeader.caplen = packet->data_length;
	packetHeader.len = packet->pcapPacketLength;
	struct iovec wvec[2];
	wvec[0].iov_base = &packetHeader;
	wvec[0].iov_len = sizeof(packetHeader);
	wvec[1].iov_base = packet->data;
	wvec[1].iov_len = packetHeader.caplen;
	if (writev(pcapFile, wvec, 2)!=(ssize_t)(sizeof(packetHeader)+packetHeader.caplen)) {
		if (errno==EAGAIN) {
			// pipe is full, drop packet
			statBytesDropped += packet->data_length;
			statPktsDropped++;
		} else
			THROWEXCEPTION("PCAPExporterPipe: failed to write, error %u (%s)", errno, strerror(errno));
	} else {
		statBytesForwarded += packet->data_length;
		statPktsForwarded++;
	}

	packet->removeReference();
	DPRINTFL(MSG_VDEBUG, "PCAPExporterPipe::receive() ended");
}
Example #13
0
/**
 * @brief VLC filter callback
 * @return picture(s) containing the filtered frames
 */
 static picture_t* y4m_filter(filter_t* intf, picture_t* srcPic)
{
    filter_sys_t* sys = intf->p_sys;

    //msg_Info(intf, ">>>> filter");

    if (!srcPic)
    {
        //msg_Info(intf, ">>> filter: NULL INPUT");
        return NULL;
    }

    // will be stored to sys->lastDate on return
    mtime_t currDate = srcPic->date;


    // if there was a problem with the subprocess then send back
    // the picture unmodified, at least we won't freeze up vlc
    if (sys->startFailed || sys->threadExit)
        goto ECHO_RETURN;


    // start subprocess and write the y4m header
    // fixme: this can go in open() if fmt_in matches the srcPic
    if (!sys->startFailed && !sys->childPid)
    {
        sys->startFailed = !startProcess(intf);
        if (sys->startFailed)
            goto ECHO_RETURN;

        if (0 >= writeY4mHeader(intf, srcPic, sys->stdin))
        {
            msg_Err(intf, "writeY4mHeader failed: errno=%d %s",
                errno, strerror(errno));

            stopProcess(intf);
            sys->startFailed = true;

            goto ECHO_RETURN;
        }
    }

    //
    // control the buffering level by monitoring the input/output fifos
    //
    // the input/output fifos are emptied/filled by input/output threads
    // in response to the subprocess reading/writing frames
    //
    // if the input fifo is empty, then probably the subprocess wants
    // more input, so we should buffer more input
    //
    // if the output fifo is empty, and the input fifo is not empty, then
    // probably the subprocess is about to write out a frame and we
    // can wait for it to arrive. in practice, most of the time there
    // is no waiting needed, unless the filter is too slow to keep up.
    //
    bool inputEmpty = true;
    bool outputEmpty = true;

    picture_t* tmp = picture_fifo_Peek(sys->inputFifo);
    if (tmp)
    {
        picture_Release(tmp);
        inputEmpty = false;
    }

    tmp = picture_fifo_Peek(sys->outputFifo);
    if (tmp)
    {
        picture_Release(tmp);
        outputEmpty = false;
    }

    // copy picture to input fifo, we can't use picture_Hold or else
    // the decoder or vout would run out of pictures in its pool
    picture_t* inPic = picture_NewFromFormat(&srcPic->format);
    picture_Copy(inPic, srcPic);
    picture_fifo_Push(sys->inputFifo, inPic);

    // signal input thread to wake up and write some more data out
    vlc_mutex_lock(&sys->inputMutex);
    sys->bufferedIn++;
    vlc_cond_signal(&sys->inputCond);
    vlc_mutex_unlock(&sys->inputMutex);

    // if echo is enabled, we're done
    // todo: there should be a limiter on the input buffering in case
    // the subprocess can't keep up
    if (sys->echo)
        goto ECHO_RETURN;


    // keeps track of the number of buffered output pictures, assumes
    // an integer ratio
    // fixme: needs modification to support non-integer ratios
    // and ratios < 1
    sys->bufferedOut += sys->bufferRatio;

    // handle buffering
    if (outputEmpty && inputEmpty)
    {
        // we haven't supplied enough input, raise the minimum
        // level of buffer to keep and return
        sys->minBuffered += sys->bufferRatio;

        msg_Info(intf, "buffer more input: buffers:%d:%d:%d",
                sys->bufferedIn, sys->bufferedOut, sys->minBuffered);

        goto NULL_RETURN;
    }

    if (outputEmpty)
        waitForOutput(intf);

    // if we don't know what the frame interval is, make it 0 which
    // probably causes the next frames out to drop
    // note: this happens at least every time y4m_flush() is called
    // for example when seeking
    if (currDate <= sys->lastDate || sys->lastDate == 0)
    {
        //msg_Err(intf, "currDate <= lastDate");
        //goto ECHO_RETURN;
        sys->lastDate = currDate;
    }

    // reference to first and last picture we are returning
    picture_t* first = NULL;
    picture_t* last = NULL;


    picture_t* pic;
    while( (pic = picture_fifo_Pop(sys->outputFifo)) )
    {
        // do output setup when we see the first frame out from the filter,
        // it could have a different frame rate, chroma, size, etc than
        // the frame going in
        if (!sys->gotFirstOutput)
        {
            sys->gotFirstOutput = true;

            // get the in/out frame ratio by comparing frame rates
            float speed =
                    ((float)srcPic->format.i_frame_rate_base * (float)pic->format.i_frame_rate) /
                    ((float)srcPic->format.i_frame_rate      * (float)pic->format.i_frame_rate_base);

            if (speed < 1.0)
            {
                msg_Err(intf, "frame rate reduction isn't supported yet");
            }
            else
            if (speed > 1.0)
            {
                if (ceil(speed) != speed)
                    msg_Err(intf, "frame rate change must be integer ratio");

                sys->bufferRatio = speed;

                // initial ratio was 1.0, need to correct the number of buffered frames
                // now that we know what it is
                sys->bufferedOut *= sys->bufferRatio;
                sys->minBuffered *= sys->bufferRatio;
            }

            intf->fmt_out.video.i_frame_rate = pic->format.i_frame_rate;
            intf->fmt_out.video.i_frame_rate_base = pic->format.i_frame_rate_base;

            if (intf->fmt_out.video.i_chroma != pic->format.i_chroma)
                msg_Err(intf, "filter changed the chroma, expect corruption");

            // this can't be changed after open, crashes the GLX vout
            //intf->fmt_out.i_codec = pic->format.i_chroma;
            //intf->fmt_out.video.i_chroma = pic->format.i_chroma;

            msg_Info(intf, "first output: buffers=%d:%d", sys->bufferedOut, sys->minBuffered);
        }

        sys->numFrames++;
        sys->bufferedOut--;

        // it seems filter_NewPicture is required now. however,
        // sometimes it returns null in which case it seems like
        // the best thing to do is dump frames
        picture_t* copy = first == NULL ? srcPic : filter_NewPicture(intf);
        if (!copy)
        {
            picture_Release(pic);

            // throw away frames

            // vlc already prints warning for this
            //msg_Err(intf, "filter_NewPicture returns null");
            if (sys->bufferedOut < sys->minBuffered)
                break;
            else
                continue;
        }
        else
        {
            picture_CopyPixels(copy, pic);
            picture_Release(pic);
            pic = copy;
        }

        // the time per output frame interval is a fraction of the input frame time
        int frameTime = (currDate - sys->lastDate) / sys->bufferRatio;

        // the pts is whatever the current pts is minus any buffering
        // introduced by the filter
        pic->date = currDate - sys->bufferedOut*frameTime;

//        msg_Info(intf, "frame=%d buffered=%d:%d frameTime=%d ratio:%d:1 fin=%d:%d fout=%d:%d pts=%u",
//            sys->numFrames, sys->bufferedOut, sys->minBuffered,
//            frameTime, sys->bufferRatio,
//            srcPic->format.i_frame_rate, srcPic->format.i_frame_rate_base,
//            pic->format.i_frame_rate, pic->format.i_frame_rate_base,
//            (unsigned int)pic->date);

        if (last)
            last->p_next = pic;
        else
            first = pic;
        last = pic;


        // if we read too many frames on this iteration, on the next
        // one we might not have any frames available which would be
        // bad as vlc would think our intent was to drop frames
        //
        // if we stop reading before the output is completely empty,
        // there will always be some frames for the next iteration,
        // assuming the filter is fast enough to keep up
        if (sys->bufferedOut  < sys->minBuffered)
            break;

        // if there is still some input buffer left, but the fifo is
        // empty, wait for next frame to arrive. otherwise we can
        // build too much input buffering
        if (sys->bufferedIn > 1)
            waitForOutput(intf);
    }

    if (!first)
    {
        // the buffer checks should prevent from getting here, but
        // just in case prevent leaking the input picture
        picture_Release(srcPic);

        sys->minBuffered++;
    }

    sys->lastDate = currDate;
    return first;
ECHO_RETURN:
    sys->lastDate = currDate;
    //msg_Info(intf, "<<<< filter: ECHO");
    return srcPic;
NULL_RETURN:
    sys->lastDate = currDate;
    picture_Release(srcPic);
    //msg_Info(intf, "<<<< filter: NULL");
    return NULL;
}
Example #14
0
TouchEventRegister<T>::~TouchEventRegister()
{
  stopProcess();
}
deBool deProcess_kill (deProcess* process)
{
	return stopProcess(process, DE_TRUE);
}
deBool deProcess_terminate (deProcess* process)
{
	return stopProcess(process, DE_FALSE);
}
Example #17
0
/**
 * @brief Start subprocess that will do the actual filtering
 * @bool true if the start was successful
 */
static bool startProcess(filter_t* intf)
{
    filter_sys_t* sys = intf->p_sys;

    bool ok = false;
    sys->childPid = 0;
    sys->stdin = -1;
    sys->stdout = -1;

    gchar** argv;
    GError* error = NULL;

    if (!g_shell_parse_argv(sys->cmd, NULL, &argv, &error))
    {
        msg_Err(intf, "startProcess: failed to parse command line");
        return false;
    }

    const gchar* workingDir = NULL;
    gchar** envp = NULL;
    GSpawnFlags flags = G_SPAWN_SEARCH_PATH;
    GSpawnChildSetupFunc childSetup = NULL;
    gpointer userData = NULL;

    if (!g_spawn_async_with_pipes(workingDir,
                                 argv,
                                 envp,
                                 flags,
                                 childSetup,
                                 userData,
                                 &sys->childPid,
                                 &sys->stdin,
                                 &sys->stdout,
                                 NULL,
                                 &error))
    {
        // todo: check gerror, print more specific error message if possible
        msg_Err(intf, "startProcess: failed to start");
    }
    else
    {
        ok = true;
        msg_Info(intf, "startProcess: started pid=%d stdin=%d stdout=%d",
            sys->childPid, sys->stdin, sys->stdout);

        // start input/writer and output/reader threads
        // we want them to respond as soon as possible so use a high priority
        int err = vlc_clone(&sys->inputThread, inputThread, intf, VLC_THREAD_PRIORITY_OUTPUT);

        if (err == VLC_SUCCESS && !sys->echo)
            err = vlc_clone(&sys->outputThread, outputThread, intf, VLC_THREAD_PRIORITY_OUTPUT);

        if (err != VLC_SUCCESS)
        {
            msg_Err(intf, "vlc_clone failed");
            stopProcess(intf);
            ok = false;
        }
    }

    g_strfreev(argv);

    return ok;
}
void PCAPExporterMem::performShutdown()
{
    unregisterSignalHandlers();
    stopProcess();
    msg(MSG_INFO, "PCAPExporterMem: sent %llu packets, dropped %llu packets", statPktsForwarded, statPktsDropped);
}
Example #19
0
PeopleEventRegister<T>::~PeopleEventRegister()
{
  stopProcess();
}
Example #20
0
Process::~Process()
{
    stopProcess();
}
Example #21
0
void PCAPExporterPipe::performShutdown()
{
	unregisterSignalHandlers();
	stopProcess();
}
Example #22
0
void Process::stop()
{
    stopProcess();
}
Example #23
0
//-------------------------------------------------------------------------------------------------------
long AudioEffectX::dispatcher (long opCode, long index, long value, void *ptr, float opt)
{
    long v = 0;
    switch(opCode)
    {
    // VstEvents
    case effProcessEvents:
        v = processEvents ((VstEvents*)ptr);
        break;

    // parameters and programs
    case effCanBeAutomated:
        v = canParameterBeAutomated (index) ? 1 : 0;
        break;
    case effString2Parameter:
        v = string2parameter (index, (char*)ptr) ? 1 : 0;
        break;

    case effGetNumProgramCategories:
        v = getNumCategories ();
        break;
    case effGetProgramNameIndexed:
        v = getProgramNameIndexed (value, index, (char*)ptr) ? 1 : 0;
        break;
    case effCopyProgram:
        v = copyProgram (index) ? 1 : 0;
        break;

    // connections, configuration
    case effConnectInput:
        inputConnected (index, value ? true : false);
        v = 1;
        break;
    case effConnectOutput:
        outputConnected (index, value ? true : false);
        v = 1;
        break;
    case effGetInputProperties:
        v = getInputProperties (index, (VstPinProperties*)ptr) ? 1 : 0;
        break;
    case effGetOutputProperties:
        v = getOutputProperties (index, (VstPinProperties*)ptr) ? 1 : 0;
        break;
    case effGetPlugCategory:
        v = (long)getPlugCategory ();
        break;

    // realtime
    case effGetCurrentPosition:
        v = reportCurrentPosition ();
        break;

    case effGetDestinationBuffer:
        v = (long)reportDestinationBuffer ();
        break;

    // offline
    case effOfflineNotify:
        v = offlineNotify ((VstAudioFile*)ptr, value, index != 0);
        break;
    case effOfflinePrepare:
        v = offlinePrepare ((VstOfflineTask*)ptr, value);
        break;
    case effOfflineRun:
        v = offlineRun ((VstOfflineTask*)ptr, value);
        break;

    // other
    case effSetSpeakerArrangement:
        v = setSpeakerArrangement ((VstSpeakerArrangement*)value, (VstSpeakerArrangement*)ptr) ? 1 : 0;
        break;
    case effProcessVarIo:
        v = processVariableIo ((VstVariableIo*)ptr) ? 1 : 0;
        break;
    case effSetBlockSizeAndSampleRate:
        setBlockSizeAndSampleRate (value, opt);
        v = 1;
        break;
    case effSetBypass:
        v = setBypass (value ? true : false) ? 1 : 0;
        break;
    case effGetEffectName:
        v = getEffectName ((char *)ptr) ? 1 : 0;
        break;
    case effGetErrorText:
        v = getErrorText ((char *)ptr) ? 1 : 0;
        break;
    case effGetVendorString:
        v = getVendorString ((char *)ptr) ? 1 : 0;
        break;
    case effGetProductString:
        v = getProductString ((char *)ptr) ? 1 : 0;
        break;
    case effGetVendorVersion:
        v = getVendorVersion ();
        break;
    case effVendorSpecific:
        v = vendorSpecific (index, value, ptr, opt);
        break;
    case effCanDo:
        v = canDo ((char*)ptr);
        break;
    case effGetIcon:
        v = (long)getIcon ();
        break;
    case effSetViewPosition:
        v = setViewPosition (index, value) ? 1 : 0;
        break;
    case effGetTailSize:
        v = getGetTailSize ();
        break;
    case effIdle:
        v = fxIdle ();
        break;

    case effGetParameterProperties:
        v = getParameterProperties (index, (VstParameterProperties*)ptr) ? 1 : 0;
        break;

    case effKeysRequired:
        v = (keysRequired () ? 0 : 1);	// reversed to keep v1 compatibility
        break;
    case effGetVstVersion:
        v = getVstVersion ();
        break;

#if VST_2_1_EXTENSIONS
    case effEditKeyDown:
        if (editor)
        {
            VstKeyCode keyCode = {index, (unsigned char)value, (unsigned char)opt};
            v = editor->onKeyDown (keyCode);
        }
        break;

    case effEditKeyUp:
        if (editor)
        {
            VstKeyCode keyCode = {index, (unsigned char)value, (unsigned char)opt};
            v = editor->onKeyUp (keyCode);
        }
        break;

    case effSetEditKnobMode:
        if (editor)
            v = editor->setKnobMode (value);
        break;

    case effGetMidiProgramName:
        v = getMidiProgramName (index, (MidiProgramName*)ptr);
        break;
    case effGetCurrentMidiProgram:
        v = getCurrentMidiProgram (index, (MidiProgramName*)ptr);
        break;
    case effGetMidiProgramCategory:
        v = getMidiProgramCategory (index, (MidiProgramCategory*)ptr);
        break;
    case effHasMidiProgramsChanged:
        v = hasMidiProgramsChanged (index) ? 1 : 0;
        break;
    case effGetMidiKeyName:
        v = getMidiKeyName (index, (MidiKeyName*)ptr) ? 1 : 0;
        break;

    case effBeginSetProgram:
        v = beginSetProgram () ? 1 : 0;
        break;
    case effEndSetProgram:
        v = endSetProgram () ? 1 : 0;
        break;

#endif // VST_2_1_EXTENSIONS

#if VST_2_3_EXTENSIONS
    case effGetSpeakerArrangement:
        v = getSpeakerArrangement ((VstSpeakerArrangement**)value, (VstSpeakerArrangement**)ptr) ? 1 : 0;
        break;

    case effSetTotalSampleToProcess:
        v = setTotalSampleToProcess (value);
        break;

    case effShellGetNextPlugin:
        v = getNextShellPlugin ((char*)ptr);
        break;

    case effStartProcess:
        v = startProcess ();
        break;
    case effStopProcess:
        v = stopProcess ();
        break;

    case effSetPanLaw:
        v = setPanLaw (value, opt) ? 1 : 0;
        break;

    case effBeginLoadBank:
        v = beginLoadBank ((VstPatchChunkInfo*)ptr);
        break;
    case effBeginLoadProgram:
        v = beginLoadProgram ((VstPatchChunkInfo*)ptr);
        break;
#endif // VST_2_3_EXTENSIONS

    // version 1.0 or unknown
    default:
        v = AudioEffect::dispatcher (opCode, index, value, ptr, opt);
    }
    return v;
}
void DialogConversionStatus::abort()
{
    resetButtons();
    emit stopProcess();
}
Example #25
0
void ProcessServer::updateDemon()
{
	dword lastRegister = 0;
	dword lastTimeSync = 0;
	dword pingTime = 0;

	while ( running() && !m_bShutdownCompleted )
	{
		Thread::sleep( 1000 );

		if (! m_MetaClient.loggedIn() )
		{
			LOG_STATUS( "ProcessServer", "Establishing connection to the metaserver" );

			// attempt to connect
			if ( m_MetaClient.open( m_Context.metaAddress, m_Context.metaPort ) > 0 )
			{
				if ( m_MetaClient.login( m_Context.uid, m_Context.pw ) < 0 )
				{
					LOG_STATUS( "ProcessServer", "Failed to login to the metaserver" );
					m_MetaClient.close();	// failed to login
				}
				else
				{
					LOG_STATUS( "ProcessServer", "Connected to the metaserver" );
					// select the correct game
					m_MetaClient.selectGame( m_Context.gameId );
				}
			}
		}
		
		m_MetaClient.update();
		if ( m_MetaClient.loggedIn() )
		{
			if ( lastRegister < (Time::seconds() - REGISTER_TIME) )
			{
				AutoLock lock( &m_Lock );

				MetaClient::Server server;
				server.gameId = m_Context.gameId;
				server.type = MetaClient::PROCESS_SERVER;
				server.flags = 0;
				server.name = m_Context.name;
				server.shortDescription.format( "CPU: %d%%, MEM: %d%%", cpuUsage(), memoryUsage() );

				server.description = server.shortDescription + "\n\n";
				for(int i=0;i<m_ProcessList.size();i++)
				{
					Process & proc = m_ProcessList[ i ];
					if ( (proc.flags & ProcessClient::PF_RUNNING) == 0 )
						continue;
					server.description += CharString().format( "%s\n", proc.name.cstr() );
				}

				server.address = m_Context.address;
				server.port = m_Context.port;
				server.maxClients = m_Context.maxClients;
				server.clients = clientCount();
				server.data = CharString().format("processGroup=%u;networkGroup=%u;processCount=%u;cpuUsage=%d;memoryUsage=%d", 
					m_Context.processGroup, m_Context.networkGroup, m_ProcessList.size(), cpuUsage(), memoryUsage() );

				lock.release();

				if ( m_MetaClient.registerServer( server ) < 0 )
					lastRegister = (Time::seconds() - REGISTER_TIME) + 30;		// failed, try again in 30 seconds
				else
					lastRegister = Time::seconds();
			}

			if ( m_Context.syncClock && lastTimeSync < (Time::seconds() - SYNC_CLOCKS_TIME) )
			{
				// get the current time from the metaserver
				dword currentTime = m_MetaClient.getTime();
				if ( currentTime > 0 )
				{
					LOG_STATUS( "ProcessServer", "Syncronizing system time to %s", Time::format( currentTime, "%c" ).cstr() );

					if (! Time::setTime( currentTime ) )
						LOG_STATUS( "ProcessServer", "Failed to set the system time!" );

					lastTimeSync = Time::seconds();
				}
				else
				{
					LOG_STATUS( "ProcessServer", "Failed to syncronize system time from MetaServer!" );
					lastTimeSync = (Time::seconds() - SYNC_CLOCKS_TIME) + 300;		// try again in another 5 min
				}
			}
		}

		AutoLock lock( &m_Lock );

		bool shutdownComplete = true;			// have all child processes stopped

		// check for log updates
		for(int i=0;i<m_ActiveLog.size();i++)
		{
			dword logId = m_ActiveLog[ i ];

			FileDisk & file = m_LogFile[ logId ];

			try {
				if ( file.position() > file.size() )
					file.setPosition( 0 );		// file has been rotated... reset read position

				dword read = file.size() - file.position();
				if ( read > 0 )
				{
					if ( read > MAX_LOG_SIZE )
					{
						file.setPosition( file.size() - MAX_LOG_SIZE );
						read = MAX_LOG_SIZE;
					}
				
					char * pLines = new char[ read + 1 ];
					pLines[ read ] = 0;

					file.read( pLines, read );

					send( m_LogClient[ logId ], ProcessClient::CLIENT_RECV_LOG_UPDATE ) << logId << CharString(pLines);

					delete [] pLines;
				}
			}
			catch( FileDisk::FileError )
			{
				LOG_STATUS( "ProcessServer", CharString().format("Log Read Error, logFile = %s, logId = %u", file.fileName(), logId) );

				// close the previously open file
				file.close();
				// attempt to reopen the file
				file.open( file.fileName() );
			}
		}

		// check process list
		for(int i=0;i<m_ProcessList.size();i++)
		{
			Process & proc = m_ProcessList[ i ];
			if ( m_ProcessInfo.find( proc.processId ).valid() )
			{
				ProcessInfo & info = m_ProcessInfo[ proc.processId ];

				proc.flags |= ProcessClient::PF_RUNNING;
				if ( (proc.flags & ProcessClient::PF_DISABLED) == 0 )
				{
					// make sure the process is still running
					if (! ::Process::active( info.m_pHandle ) )
					{
						proc.flags &= ~ProcessClient::PF_RUNNING;

						if ( ! m_Shutdown )
						{
							if ( info.m_nRestartTime != 0 && Time::seconds() < info.m_nRestartTime )
								continue;		// not time to restart yet, continue onto the next process..

							// process has exited, increment the number of restarts, then calculate the next restart
							// time increasing the wait time each time the process exits
							info.m_nRestarts += 1;
							info.m_nRestartTime = Time::seconds() + (60 * (info.m_nRestarts * info.m_nRestarts) );

							int exitCode = ::Process::exitCode( info.m_pHandle );
							::Process::close( info.m_pHandle );

							CharString message;
							message.format( "Process %u exit, name = %s, exec = %s, arg = %s, exitCode = %d, restarts = %u", 
								proc.processId, proc.name.cstr(), proc.executable.cstr(), proc.arguments.cstr(), exitCode, info.m_nRestarts );
							LOG_STATUS( "ProcessServer", message );


							// send report if exit code is negative
							if ( exitCode < 0 )
								m_MetaClient.sendChat( 0, CharString().format("/report %s", message.cstr()) );

							// restart the process..
							Path exePath( proc.executable );
							void * pStart = ::Process::start( CharString().format("%s %s", exePath.file().cstr(), proc.arguments.cstr()), 
								exePath.directory() );
							if ( pStart == NULL )
							{
								LOG_STATUS( "ProcessServer", "Process %u failed to restart", proc.processId );

								m_ProcessInfo.remove( proc.processId );
								proc.flags |= ProcessClient::PF_DISABLED;
							}
							else
							{
								LOG_STATUS( "ProcessServer", "Process %u restarted", proc.processId );
								info.m_pHandle = pStart;
							}
						}
						else
						{
							int exitCode = ::Process::exitCode( info.m_pHandle );

							LOG_STATUS( "ProcessServer", "Process Stopped, name = %s, exitCode = %d", proc.name.cstr(), exitCode );
							::Process::close( info.m_pHandle );

							m_ProcessInfo.remove( proc.processId );
						}
						
					}
					else if ( m_Shutdown )
					{
						shutdownComplete = false;	
						stopProcess( proc.processId );
					}
					else if ( info.m_nRestartTime != 0 && Time::seconds() > info.m_nRestartTime )
					{
						// process has been running long enough to clear the restart time.
						info.m_nRestartTime = 0;
						info.m_nRestarts = 0;
					}
				}
				else
				{
					if (! ::Process::active( info.m_pHandle ) )
					{
						LOG_STATUS( "ProcessServer", "Process Stopped, name = %s", proc.name.cstr() );
						::Process::close( info.m_pHandle );

						m_ProcessInfo.remove( proc.processId );
					}
					else
						stopProcess( proc.processId );
				}
			}
			else
			{
				proc.flags &= ~ProcessClient::PF_RUNNING;
				if ( (proc.flags & ProcessClient::PF_DISABLED) == 0 && !m_Shutdown )
				{
					LOG_STATUS( "ProcessServer", "Starting Process %u, name = %s, exec = %s, arg = %s", 
						proc.processId, proc.name.cstr(), proc.executable.cstr(), proc.arguments.cstr() );

					Path exePath( proc.executable );
					void * pStart = ::Process::start( CharString().format("%s %s", exePath.file().cstr(), proc.arguments.cstr()),
						exePath.directory() );
					if ( pStart == NULL )
					{
						proc.flags |= ProcessClient::PF_DISABLED;

						LOG_STATUS( "ProcessServer", "Process %u Failed to Start, name = %s, exec = %s", 
							proc.processId, proc.name.cstr(), proc.executable.cstr() );
					}
					else
						m_ProcessInfo[ proc.processId ].m_pHandle = pStart;
				}
			}
		}

		pingTime++;
		if ( pingTime > 15 )
		{
			// ping all clients
			for(int i=0;i<clientCount();i++)
				send( client(i), ProcessClient::PING );
			
			pingTime = 0;
		}

		// check for shutdown
		if ( m_Shutdown && shutdownComplete )
		{
			m_bShutdownCompleted = true;

			if ( m_RebootOnShutdown )
				rebootMachine();
		}

		lock.release();
	}
}
Example #26
0
AudioEventRegister::~AudioEventRegister()
{
  stopProcess();
}
void MgrStereoHand::initUI(){

	// rozmiar przetwarzania

	processGroup = new QButtonGroup(this);
	processGroup->addButton(ui.processButtonRadio0, VIDEO);
	//processGroup->addButton(ui.processButtonRadio1, RECORD);
	processGroup->addButton(ui.processButtonRadio2, CAMERA);
	Settings::instance()->processType = processGroup->checkedId();


	connect(processGroup,	SIGNAL(buttonClicked (int)),
			this,			SLOT(processTypeChanged(int)));

	// film
	connect(ui.buttonLoadFilm0,	SIGNAL(clicked()),
			this,				SLOT(loadFilmClicked0()));

	connect(ui.buttonLoadFilm1,	SIGNAL(clicked()),
			this,				SLOT(loadFilmClicked1()));

	// kalibracja
	connect(ui.buttonLoadCalibration,	SIGNAL(clicked()),
			this,						SLOT(loadCalibrationFile()));

	connect(ui.calibrateButton,			SIGNAL(clicked()),
			this,						SLOT(calibrateButtonClicked()));

	
	// start-stop
	connect(ui.buttonStart,		SIGNAL(clicked()),
			this,				SLOT(startProcess()));

	connect(ui.buttonStop,		SIGNAL(clicked()),
			this,				SLOT(stopProcess()));

	// pokazywane elementy przetwarzania
	connect(ui.sliderShowImage,	SIGNAL(valueChanged(int)),
			this,				SLOT(changeShowImage(int)));
	Settings::instance()->initImageType(ui.sliderShowImage->value());
	ui.labelShowImage->setText(Settings::instance()->getImageTypeString());

	// wyjscie
	connect(ui.buttonExit,		SIGNAL(clicked()),
			this,				SLOT(exit()));

	algorithmsDialog = new AlgorithmsDialog(this);
	statisticsDialog = new StatisticsDialog(this);
	calibDialog = new CalibrationDialog(this);

	connect(calibDialog,	SIGNAL(calibrationStartFromDialog()),
			this,			SLOT(startCalibrationClickedFromDialog()));

	connect(calibDialog,	SIGNAL(calibrationSaved()),
			this,			SLOT(savedCalibrationFromDialog()));


	setGeometry(10, 30, geometry().width(), geometry().height());
	
	algorithmsDialog->setGeometry(	10, geometry().height()+60, 
									algorithmsDialog->geometry().width(), 
									algorithmsDialog->geometry().height());

	statisticsDialog->setGeometry(	geometry().width()+20, 30, 
									statisticsDialog->geometry().width(), 
									statisticsDialog->geometry().height());

	calibDialog->setGeometry(	50, geometry().height(), 
									algorithmsDialog->geometry().width(), 
									algorithmsDialog->geometry().height());

	algorithmsDialog->show();
	statisticsDialog->show();
}
Example #28
0
/*!
 * \brief MainWindow::MainWindow
 * \param parent
 */
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent),
      ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    ui->stopButton->hide();

    ui->qwtPlot->setTitle("Error");
    ui->qwtPlot->setAxisTitle(ui->qwtPlot->xBottom, "Epoch");
    ui->qwtPlot->setAxisTitle(ui->qwtPlot->yLeft,"Error");
    ui->qwtPlot->setAxisAutoScale( ui->qwtPlot->xBottom, true );
    ui->qwtPlot->setAxisAutoScale( ui->qwtPlot->yLeft, true );
    ui->stopButton->setVisible( false );
    ui->saveButton->setVisible( false );
    zoom = new QwtPlotZoomer(ui->qwtPlot->canvas());
    zoom->setRubberBandPen(QPen(Qt::white));
    QPen pen = QPen( Qt::red );
    curve.setRenderHint( QwtPlotItem::RenderAntialiased );
    curve.setPen( pen );
    curve.attach( ui->qwtPlot );
    sendAlpha();

    // INFO connect ui to mainwindow
    {
        QObject::connect( ui->saveImageButton, SIGNAL( clicked() ),
                          this, SLOT( saveImage() ) );
       QObject::connect( ui->inputOpenButton, SIGNAL( clicked() ),
                          this, SLOT( openInputFile() ) );
        QObject::connect( ui->saveButton, SIGNAL( clicked() ),
                          this, SLOT( openOutputFile() ) );
        QObject::connect( ui->startButton, SIGNAL( clicked() ),
                          this, SLOT( start() ) );
        QObject::connect( ui->startButton, SIGNAL( clicked( bool ) ),
                          ui->stopButton, SLOT( setVisible(bool) ) );
        QObject::connect( ui->alphaMantiss, SIGNAL( valueChanged( double ) ),
                          this, SLOT( sendAlpha() ) );
        QObject::connect( ui->alphaDegree, SIGNAL( valueChanged( int ) ),
                          this, SLOT( sendAlpha() ) );
    }

    // INFO connectio ui to ui
    {
        QObject::connect(ui->startButton,SIGNAL(clicked()),ui->stopButton,SLOT(show()));
    }
//    /* INFO connection ui to facade
    {
        QObject::connect( ui->stopButton, SIGNAL( clicked() ),
                          &Facade::getInstance(), SLOT( stopProcess() ) );

        QObject::connect( ui->maxEpoch, SIGNAL( valueChanged(int) ),
                          &Facade::getInstance(), SLOT( setMaxNumberOfEpoh(int) ) );

        QObject::connect( ui->numberOfNeurons, SIGNAL( valueChanged(int) ),
                          &Facade::getInstance(), SLOT( setNumberOfNeurons(int) ) );

    }
//    */
//    /* INFO connection facade to ui
    {
        QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ),
                          ui->startButton, SLOT( show() ) );
        QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ),
                          ui->saveButton, SLOT( show() ) );
        QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ),
                          ui->stopButton, SLOT( hide() ) );
    }
//    */
//    /* INFO connection facade to main window
    {
//        QObject::connect( &Facade::getInstance(), SIGNAL( sendInitialLayerInfo(LayerDescription)),
//                          this, SLOT( setInitialLayerInfo( LayerDescription ) ) );
        QObject::connect( &Facade::getInstance(), SIGNAL( processEnd() ),
                          this, SLOT( displayResults() ) );
    }
//    */
//    /* INFO connection main window to facade
    {
        QObject::connect( this, SIGNAL( setInputFileName(QString) ),
                          &Facade::getInstance(), SLOT( setInputFileName(QString) ) );
        QObject::connect( this, SIGNAL( setOutputFileName(QString) ),
                          &Facade::getInstance(), SLOT( setOutputFileName(QString) ) );
        QObject::connect( this, SIGNAL( setAlpha( double ) ),
                          &Facade::getInstance(), SLOT( setAlhpa( double ) ) );
    }
//    */
}