summaryrefslogtreecommitdiff
path: root/daemon.sh
blob: 3fcbc994a7be8af3dd60e894e8dc841109d9fad0 (plain)
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
46
47
48
49
50
51
#!/bin/bash

get_ident() {
	local pid=$1
	ps h -o lstart -p "$pid"
}

is_running() {
	local pidfile=$1
	if [[ -f "$pidfile" ]]; then
		read -r pid ident1 <"$pidfile"
		ident2="$(get_ident "$pid")"
		if [[ "$ident1" == "$ident2" ]] && [[ -n "$ident2" ]]; then
			return 0
		else
			return 1
		fi
	else
		return 1;
	fi
}

main() {
	# Parse arguments
	if [[ $1 = '-i' ]]; then
		shift
		id=$1
		shift
	else
		id=$1
	fi

	# Init variables
	TMP=${TMPDIR-/tmp}/daemon
	PIDFILE="$TMP/$id.pid"
	OUTFILE="$TMP/$id.out"
	ERRFILE="$TMP/$id.err"

	# Run
	if is_running "$PIDFILE"; then
		echo "daemon: \`$id' is already running"
	else
		mkdir -p "$TMP"
		echo "daemon: starting \`$id'"
		nohup "$@" > "$OUTFILE" 2> "$ERRFILE" &
		pid=$!
		echo "$pid" "`get_ident $pid`" > "$PIDFILE"
	fi
}

main "$@"