Our react game – how it works

So, at a high level, here's the step-by-step plan for the program (the actual code is shown in the following section; we suggest you first read this and then check out the code):

  • Create and initialize a simple alarm; program it to expire at a random time—anywhere between 1 and 5 seconds from the program's start
  • The moment the alarm expires, do the following:
    • Arm a POSIX (interval) timer (to the frequency specified in the first parameter).
    • Display a message requesting the user to press Ctrl C on the keyboard
    • Take a timestamp (let's call it tm_start).
  • When the user actually presses ^C (Ctrl C; which we will know, simply, by trapping SIGINT via sigaction(2)), again, take a timestamp (let's call it tm_end.
  • Calculate the user's reaction time (as tm_end - tm_start) and display it.

(Notice how the previous steps follow the Typical application workflow we described earlier in this chapter.)

Additionally, we ask the user to specify the interval timer's interval in milliseconds (the first parameter), and an optional verbose option as the second parameter.

Breaking it down further (in more detail), the initialization code performs the following:

  • Traps signals via sigaction(2):
    • SIGRTMIN: We shall use signal notification to specify the timer expiration; this is the signal generated upon our POSIX interval timer's expiry.
    • SIGINT: The signal generated when the user reacts by pressing the ^C keyboard key combination.
    • SIGALRM: The signal generated when our initial random alarm expires
  • Set up the POSIX interval timer:
    • Initialize the sigevent structure.
    • Create the timer (with a real-time clock source) with timer_create(2).
    • Initialize the itimerspec structure to the frequency value specified by the user (in ms)

Then:

  • Displays a message to the user:
We shall start a timer anywhere between 1 and 5 seconds of starting this app.

GET READY ...
[ when the "QUICK! Press ^C" message appears, press ^C quickly as you can ]

  • At any random time between 1 and 5 seconds the alarm expires
  • We enter the SIGALRM handler function
    • It displays the *** QUICK! Press ^C !!! *** message
    • It calls timer_settime(2) to arm the timer
    • It takes the tm_start timestamp (with the clock_gettime(2) API) 
    • The POSIX interval timer now runs; it expires every freq_ms milliseconds (the value provided by the user); when running in verbose mode, we display a . for each timer expiry
  • The user, at some point, near or far, reacts and presses Ctrl C(^C); in the code for the signal handler for SIGINT, we do the following:
    • Take the tm_end timestamp (with the clock_gettime(2) API) 
    • Calculate the delta (the reaction time!) via tm_end - tm_start, and display it
  • Exit.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.191.52.96