CS 355 - Systems Programming:
Unix/Linux with C

Event-Driven Programming

Reference: Molay, Understanding Unix/Linux Programming, Chapter 7.1-7.6

Video games and operating systems

Space
Video game: control video display to draw images at specific locations on the screen.
OS: kernel loads programs into memory space and keeps track of the location of each program.
Time
Video game: images move of the screen at different speeds; events occur with different intervals.
OS: kernel schedules programs to run for short intervals; schedules internal tasks to be done at different times.
Interruptions
Video game: users can send input to the game whenever they like.
OS: kernel must respond quickly to the input sent at unpredictable times by users and other external devices.
Multitasking
Video game: must keep multiple objects moving and respond to input at the same time.
OS: kernel must be able to run multiple processes and respond to input at the same time.

Space programming: the curses library

Allows the programmer to set set the position of the cursor and control the appearance of text on a terminal screen. The screen is treated as a 2D array. Each location is identified by the (row, column) pair of values with (0,0) at the upper left corner of the screen. Uses a virtual screen where all changes are made. Function refresh() is used to apply these changes to the actual screen.

Basic curses functions:

initscr()
Initializes the curses library and the tty
endwin()
Turns off curses library and the tty
refresh()
Updates the screen
move(r,c)
Moves the cursor to the position (r,c)
addstr(s)
Draws string s on the screen in the current position
addch(c)
Draws char c on the screen in the current position
clear()
Clears the screen

Time programming: sleep()

Function sleep(unsigned int s) suspend thread execution for an interval of s seconds.

#include <stdio.h>
#include <curses.h>

main() {
   int i;
   initscr();
   clear();
   for(i=0; i<LINES; i++ ){
      move( i, i+i );
      addstr("Hello, world");
      refresh();
      sleep(1);
      move(i,i+i);               /* move back    */
      addstr("             ");   /* erase line   */
   }
   endwin();
}

Time programming: alarm()

sleep(n) works as follows:

signal(SIGALRM, handler);   /* install a handler for alarm */
alarm(n);                   /* set the alarm               */
pause();                    /* suspend the execution       */

Time programming: interval timers

int getitimer(int which, struct itimerval *val);
int setitimer(int which, const struct itimerval *newval, struct itimerval *oldval);

Use the set_ticker() function described on p. 213 to set an interval timer.