Debian Codegraph @

timed-input.sh

raw symbols SCIP
1 #!/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 PrintAnswer()
11 {
12 if [ "$answer" = TIMEOUT ]
13 then
14 echo $answer
15 else # Don't want to mix up the two instances.
16 echo "Your favorite veggie is $answer"
17 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 TimerOn()
26 {
27 sleep $TIMELIMIT && kill -s 14 $$ &
28 # Waits 3 seconds, then sends sigalarm to script.
29 }
30
31
32 Int14Vector()
33 {
34 answer="TIMEOUT"
35 PrintAnswer
36 exit $TIMER_INTERRUPT
37 }
38
39 trap Int14Vector $TIMER_INTERRUPT
40 # Timer interrupt (14) subverted for our purposes.
41
42 echo "What is your favorite vegetable "
43 TimerOn
44 read answer
45 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