-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbash_daemon.sh
More file actions
47 lines (32 loc) · 745 Bytes
/
bash_daemon.sh
File metadata and controls
47 lines (32 loc) · 745 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/bin/bash
SLEEP=3
WORK_DIR="$( cd -- "$( dirname -- "${BASH_SOURCE[0]}" )" &> /dev/null && pwd )"
PID_FILE="$WORK_DIR/bash_daemon.pid"
#Try get lock for pidfile or exit
exec 100>>"$PID_FILE"
flock -xn 100 || { echo "Already running. Exit"; exit 114;}
PID=$$
#write PID to pidfile
echo "$PID" >&100
#write all to log
exec 1>>"$WORK_DIR/bash_daemon.log" 2>&1
#close stdin
exec 0<&-
write_log() {
echo "$(date '+%d.%m.%Y %H:%M:%S') - $1"
}
cleanup() {
write_log "EXIT pid=$PID"
return_value=$?
rm -rf "$PID_FILE"
exit $return_value
}
trap "cleanup" EXIT
#ignore SIGHUP when terminal closes
trap "write_log 'GET SIGHUP'" SIGHUP
write_log "START pid=$PID"
while true;
do
#YOUR COMMAND
sleep $SLEEP
done;