#include #include #include using namespace std; const int TIMESLICE=3; bool alarmFired = false; /* * void sigalarm_handler(int signum) * User defined signal handler for the signal number that is registered * using signal(unsigned int signum, sighandler_t) * @param signum: signal number of the signal that caused the handler to fire. */ void sigalarm_handler(int signum) { // To simulate a preemptive, timesliced scheduling system, a signal handler // must be registered that simulates the CPU timer that fires whenever the // system has to schedule another process. cout << "got signal " << signum << endl; alarmFired = true; } /* * main(void) * Demonstrates the use of signal to register a signal handler for a signal * as well as the use of alarm to set an alarm for TIMESLICE seconds. Then * the process sleeps for some arbitrary amount of time. The process awakens * due to the alarm since the sleep time is greater than the alarm time. */ int main(void) { int timeRemaining = 16; signal(SIGALRM, sigalarm_handler); cout << "pid is " << getpid() << endl; while (timeRemaining > 0) { // Set the alarm each time through for the prescribed number of seconds. alarm(TIMESLICE); // Simulate CPU time with either sleep(int seconds) or // settimer(ITIMER_REAL, const struct itimerval *newval, struct itimerval *oldval) // Get the sleep seconds from the remaining process time. sleep(timeRemaining); cout << "ProcessName " << timeRemaining << endl; // If alarm has fired, then timeslice expired, // otherwise remaining time expired. if (alarmFired == true) timeRemaining -= TIMESLICE; else timeRemaining -= timeRemaining; // Print that process is finished if no time remaining. if (timeRemaining == 0) cout << "ProcessName finished" << endl; // Reset alarmFired. alarmFired = false; } }