Debian Codegraph @

timed-input.sh

raw symbols SCIP
1 #!/bin/bashscip-shell filesystem . . `/bin/bash`.
2 # timed-input.sh
3
4 # TMOUT=3 Also works, as of newer versions of Bash.
5
6 TIMER_INTERRUPT=14
7 TIMELIMIT=3 # Three seconds in this instance.
8 # May be set to different value.
9
10 PrintAnswerscip-shell shell abs-guide 10-4 PrintAnswer().()
11 {
12 if [scip-shell system . . `[`. "$answer" = TIMEOUT ]
13 then
14 echoscip-shell system . . echo. $answer
15 else # Don't want to mix up the two instances.
16 echoscip-shell system . . echo. "Your favorite veggie is $answer"
17 killscip-shell system . . kill. $! # Kills no-longer-needed TimerOn function
18 #+ running in background.
19 # $! is PID of last job running in background.
20 fi
21
22 }
23
24
25 TimerOnscip-shell shell abs-guide 10-4 TimerOn().()
26 {
27 sleepscip-shell system . . sleep. $TIMELIMIT && killscip-shell system . . kill. -s 14 $$ &
28 # Waits 3 seconds, then sends sigalarm to script.
29 }
30
31
32 Int14Vectorscip-shell shell abs-guide 10-4 Int14Vector().()
33 {
34 answer="TIMEOUT"
35 PrintAnswerscip-shell shell abs-guide 10-4 PrintAnswer().
36 exit $TIMER_INTERRUPT
37 }
38
39 trap Int14Vector $TIMER_INTERRUPT
40 # Timer interrupt (14) subverted for our purposes.
41
42 echoscip-shell system . . echo. "What is your favorite vegetable "
43 TimerOnscip-shell shell abs-guide 10-4 TimerOn().
44 read answer
45 PrintAnswerscip-shell shell abs-guide 10-4 PrintAnswer().
46
47
48 # Admittedly, this is a kludgy implementation of timed input.
49 # However, the "-t" option to "read" simplifies this task.
50 # See the "t-out.sh" script.
51 # However, what about timing not just single user input,
52 #+ but an entire script?
53
54 # If you need something really elegant ...
55 #+ consider writing the application in C or C++,
56 #+ using appropriate library functions, such as 'alarm' and 'setitimer.'
57
58 exit 0