Commit | Line | Data |
---|---|---|
4411059d SK |
1 | #! /bin/bash |
2 | ||
3 | set -e | |
4 | ||
5 | # Defaults | |
6 | prefix='/dev/shm/khatus' | |
7 | host="$(hostname)" | |
8 | sensor="$(basename $0)" | |
9 | run_in='foreground' # foreground | background | |
10 | run_as='poller' # poller | streamer | |
11 | interval=1 # Only relevant if run_as poller, ignored otherwise. | |
12 | ||
13 | set_common_options() { | |
14 | while : | |
15 | do | |
16 | case "$1" | |
17 | in '') | |
18 | break | |
19 | ;; -d|--daemon) | |
20 | run_in='background' | |
21 | shift 1 | |
22 | ;; -i|--interval) | |
23 | case "$2" | |
24 | in '') | |
25 | printf "Option $1 requires and argument\n" >&2 | |
26 | exit 1 | |
27 | ;; *) | |
28 | interval="$2" | |
29 | shift 2 | |
30 | esac | |
31 | ;; *) | |
32 | shift 1 | |
33 | esac | |
34 | done | |
35 | } | |
36 | ||
37 | init_dirs() { | |
38 | work_dir="${prefix}/${host}/${sensor}" | |
39 | out_dir="${work_dir}/out" | |
40 | err_file="${work_dir}/err" | |
41 | pid_file="${work_dir}/pid" | |
42 | ||
43 | mkdir -p "$out_dir" | |
44 | } | |
45 | ||
46 | streamer() { | |
47 | sensor \ | |
48 | | while read key val | |
49 | do | |
50 | printf "%s\n" "$val" > "${out_dir}/${key}" | |
51 | done | |
52 | >> "$err_file" | |
53 | } | |
54 | ||
55 | poller() { | |
56 | while : | |
57 | do | |
58 | streamer | |
59 | sleep "$interval" | |
60 | done | |
61 | } | |
62 | ||
63 | pid_file_create_of_parent() { | |
64 | printf "$$\n" > "$pid_file" | |
65 | } | |
66 | ||
67 | pid_file_create_of_child() { | |
68 | printf "$!\n" > "$pid_file" | |
69 | } | |
70 | ||
71 | pid_file_test() { | |
72 | if test -e "$pid_file" | |
73 | then | |
74 | printf "Error - $sensor already running (i.e. PID file exists at $pid_file)\n" 1>&2 | |
75 | exit 1 | |
76 | fi | |
77 | } | |
78 | ||
79 | pid_file_remove() { | |
80 | rm -f "$pid_file" | |
81 | } | |
82 | ||
83 | run_in_foreground() { | |
84 | # TODO: Why do INT and EXIT traps only work in combination? | |
85 | trap true INT | |
86 | trap exit TERM | |
87 | trap pid_file_remove EXIT | |
88 | $run_as | |
89 | } | |
90 | ||
91 | run_in_background_2nd_fork() { | |
92 | run_in_foreground & | |
93 | pid_file_create_of_child | |
94 | } | |
95 | ||
96 | run_in_background() { | |
97 | run_in_background_2nd_fork & | |
98 | } | |
99 | ||
100 | run() { | |
101 | case "$run_as" | |
102 | in 'poller' | 'streamer') | |
103 | true | |
104 | ;; *) | |
105 | printf "Error - illegal value for \$run_as: $run_in\n" 1>&2 | |
106 | exit 1 | |
107 | esac | |
108 | pid_file_test | |
109 | case "$run_in" | |
110 | in 'background') | |
111 | run_in_background | |
112 | ;; 'foreground') | |
113 | pid_file_create_of_parent | |
114 | run_in_foreground | |
115 | ;; *) | |
116 | printf "Error - illegal value for \$run_in: $run_in\n" 1>&2 | |
117 | exit 1 | |
118 | esac | |
119 | } | |
120 | ||
121 | set_common_options $@ | |
122 | init_dirs |