#include #include #include const int TIMESLICE=3; /* * 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. printf("got SIGALRM %d\n", signum); } /* * 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 usleeps for some arbitrary amount of time. The process awakens * due to the alarm when the usleep time is greater than the alarm time otherwise * it wakens due to usleep completing. */ int main(void) { signal(SIGALRM, sigalarm_handler); printf("pid is %d\n", getpid()); int sleeptimes[] = { 1000000, 2000000, 6000000, 7000000 }; int index = 0; while (true) { // Set the the alarm each time through for the prescribed number of seconds. alarm(TIMESLICE); // Simulate CPU time with either usleep(int microseconds) or // settimer(ITIMER_REAL, const struct itimerval *newval, struct itimerval *oldval) // get the seconds from the remaining process time. usleep(sleeptimes[index]); printf("loop again=%d; \n", sleeptimes[index]); index = ((index+1) % (sizeof(sleeptimes)/sizeof(int))); } }