File: sxmo_daemons.sh

package info (click to toggle)
sxmo-utils 1.14.2-1.1
  • links: PTS, VCS
  • area: main
  • in suites: experimental
  • size: 6,016 kB
  • sloc: sh: 9,166; ansic: 117; makefile: 68
file content (129 lines) | stat: -rwxr-xr-x 1,831 bytes parent folder | download
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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
#!/bin/sh
# SPDX-License-Identifier: AGPL-3.0-only
# Copyright 2022 Sxmo Contributors

# include common definitions
# shellcheck source=scripts/core/sxmo_common.sh
. sxmo_common.sh

ROOT="$XDG_RUNTIME_DIR/sxmo_daemons"
mkdir -p "$ROOT"

exec 3<> "$ROOT/daemons.lock"
flock -x 3

list() {
	find "$ROOT" -mindepth 1 -exec 'basename' '{}' ';'
}

stop() {
	while [ "$#" -gt 0 ]; do
		case "$1" in
			-f)
				force=1
				shift
				;;
			*)
				id="$1"
				shift
				break
				;;
		esac
	done

	case "$id" in
		all)
			list | while read -r sub_id; do
				stop "$sub_id"
			done
			;;
		*)
			if [ -f "$ROOT/$id" ]; then
				sxmo_debug "stop $id"
				xargs kill ${force:+-9} < "$ROOT"/"$id" 2> /dev/null
				rm "$ROOT"/"$id"
			fi
			;;
	esac
}

signal() {
	id="$1"
	shift

	if [ -f "$ROOT/$id" ]; then
		sxmo_debug "signal $id $*"
		xargs kill "$@" < "$ROOT"/"$id" 2> /dev/null
	fi
}

start() {
	while [ "$#" -gt 0 ]; do
		case "$1" in
			--no-restart)
				no_restart=1
				shift
				;;
			*)
				id="$1"
				shift
				break
				;;
		esac
	done

	if [ -f "$ROOT/$id" ]; then
		if [ -n "$no_restart" ]; then
			sxmo_debug "$id already running"
			exit 1
		else
			stop "$id"
		fi
	fi

	sxmo_debug "start $id"
	(
		# We need a subshell so we can close the lock fd, without
		# releasing the lock
		exec 3<&-
		"$@" &
		printf "%s\n" "$!" > "$ROOT"/"$id"
	)
}

running() {
	while [ "$#" -gt 0 ]; do
		case "$1" in
			-q)
				quiet=1
				shift
				;;
			*)
				id="$1"
				shift
				;;
		esac
	done

	log() {
		if [ -z "$quiet" ]; then
			# shellcheck disable=SC2059
			printf "$@"
		fi
	}

	if [ -f "$ROOT/$id" ]; then
		pid="$(cat "$ROOT/$id")"
		if [ -d "/proc/$pid" ]; then
			log "%s is still running\n" "$id"
		else
			log "%s is not running anymore\n" "$id"
			exit 2
		fi
	else
		log "%s is not running\n" "$id"
		exit 1
	fi
}

"$@"