/*****************************************************************************
 * File: Process.cpp
 * -----------------------
 * description: this module implements all functionalities to spawn the realtime
 * process from within the background process.

 * author: M. Zinn	
 * date:   2/1/2001	
 *      
 * revision history:
 * 7/24/2003 - P. Thaulad (migrated to QNX 6.0) in preparation for the new ARM
 * project
 *****************************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sched.h>

#include "Process.h"
#include "Definitions.h"
#define PROCESS_PRIORITY	50	// slow process priority, max is 22

#define SPAWN_FILE2	"user"

void Process::Spawn_RT (void)
{
	// spawn the process; SPAWN_FILE defined in .h

	realtime_pid = spawnl(P_NOWAIT, SPAWN_FILE, SPAWN_FILE, NULL);

	if(realtime_pid == -1)
	{
		perror("printer spawning failed");
		exit(1);
	}

	printf("Realtime spawning success \n");
/*	realtime_pid2 = spawnl(P_NOWAIT, SPAWN_FILE2, SPAWN_FILE2, NULL);

	if(realtime_pid2 == -1)
	{
		perror("user process spawning failed");
		exit(1);
	}
*/
	printf("Realtime spawning success \n");


	delay(10);	// delay for # ms to allow other process to start
}

void Process::Get_Background_pid(void)
{
	background_pid = getppid();
}

void Process::Is_Background_Alive(void)
{
	// kill(ppid, message) pokes the process and see if it's still alive
	if(kill(background_pid,FALSE) == -1)
	{
		printf("Background process terminated abnormally \n");
		exit(1);
	}

	else
		printf("Background process is alive \n");
}

int Process::Is_RT_Alive(void)
{
	// realtime_pid was assigned during the original spawning
	if(kill(realtime_pid, FALSE) == -1)
	{
		printf("realtime process terminated abnormally \n");
		return(FALSE);
	}

	else
	{
		printf("realtime process is alive \n");
		return(TRUE);
	}
		
}

void Process::Kill_RT_Process(void)
{
	delay(2000);

	kill(realtime_pid, FALSE);
//	kill(realtime_pid2, FALSE);
	printf("realtime processes terminated \n");
/*
	if(kill(realtime_pid, FALSE) == -1)
		return;

	if(kill(realtime_pid, TRUE) == 0)
	{
		printf("realtime process terminated \n");
		return;
	}

	printf("Realtime process could not be terminated \n");
*/

}

void Process::Set_Realtime_Priority(void)
{
	struct sched_param sched;	// struct form defined in sched.h
	int i;

	i = sched_getparam(0,&sched);
	printf("RT schedule previous priority: %d \n", sched.sched_priority);

	sched.sched_priority = PROCESS_PRIORITY; // def in global_defs.h

	i = sched_setscheduler(0, SCHED_FIFO, &sched);

	if(i == -1)
	{
		perror("Error in setting RT priority");
		exit(1);
	}
	else
	{
		i = sched_getparam(0,&sched);
		printf("Printer process schedule set to %d \n", sched.sched_priority);
	}


}


	






