#include #include #include #include /* * bounce1d2.c * purpose animate using curses and alarm * demonstrate ASYNC io * note one handler does the animation * one handler processes keyboard input * the main program just pause()es * compile cc bounce1.c set_ticker.c -lcurses -o bounce1 */ /* * some global vars that main and the handler use */ #define MESSAGE " hello " int row; /* current row */ int col; /* current column */ int dir; /* where we are going */ int done = 0; int delay; /* bigger => slower */ int main() { void on_ticker(); /* handler for timer */ void on_keypress(); /* handler for keyboard */ initscr(); crmode(); noecho(); clear(); row = 10; /* start here */ col = 0; dir = 1; delay = 200; /* 200ms = 0.2 seconds */ move(row,col); /* get into position */ addstr( MESSAGE ); /* note spaces */ signal(SIGALRM, on_ticker ); set_ticker( delay ); signal(SIGIO, on_keypress); if ( fcntl(0, F_SETOWN, getpid()) == -1 ){ perror("setown"); exit(1); } if ( fcntl(0, F_SETFL, O_ASYNC) == -1 ){ perror("setfl"); exit(1); } while( !done ){ pause(); } endwin(); return 0; } void on_keypress() { char x[100]; int i,n; int ndelay; /* new delay */ int c; /* user input */ n = read(0, x, 100); for(i=0; i 2 ) ndelay = delay/2; if ( c == 's' ) ndelay = delay * 2; if ( ndelay > 0 ){ set_ticker( delay = ndelay ); } } } void on_ticker() { signal(SIGALRM, on_ticker); /* reset, just in case */ col += dir; /* move to new column */ move( row, col ); /* then set cursor */ addstr( MESSAGE ); /* redo message */ refresh(); /* and show it */ /* * now handle borders */ if ( dir == -1 && col == 0 ) dir = 1; else if ( dir == 1 && col+strlen(MESSAGE) >= COLS ) dir = -1; }