#!/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_jobs" mkdir -p "$ROOT" exec 3<> "$XDG_RUNTIME_DIR/sxmo.jobs.lock" flock -x 3 list() { for f in "$ROOT"/*; do [ -e "$f" ] || continue case "$f" in *.group) continue ;; esac printf "%s\n" "${f##*/}" done } 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.group" ]; then sxmo_debug "stop group $id" read -r pid < "$ROOT/$id.group" 2>/dev/null || pid="" [ -n "$pid" ] && kill ${force:+-9} -- "-$pid" 2> /dev/null || true elif [ -f "$ROOT/$id" ]; then sxmo_debug "stop $id" read -r pid < "$ROOT/$id" 2>/dev/null || pid="" [ -n "$pid" ] && kill ${force:+-9} "$pid" 2> /dev/null || true fi rm -f "$ROOT/$id" "$ROOT/$id.group" 2>/dev/null || true ;; esac } signal() { id="$1" shift if [ -f "$ROOT/$id" ]; then sxmo_debug "signal $id $*" read -r pid < "$ROOT/$id" 2>/dev/null || pid="" [ -n "$pid" ] && kill "$@" "$pid" 2> /dev/null || true fi } start() { while [ "$#" -gt 0 ]; do case "$1" in --no-restart) no_restart=1 shift ;; --group) has_group=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" # Start job in a new session, close the lock fd, and record PID synchronously # before releasing the jobs lock so subsequent stop calls never race. setsid "$@" 3<&- & job_pid=$! printf "%s\n" "$job_pid" > "$ROOT/$id" if [ -n "$has_group" ]; then printf "%s\n" "$job_pid" > "$ROOT/$id.group" fi } 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 read -r pid < "$ROOT/$id" 2>/dev/null || pid="" if [ -n "$pid" ] && [ -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 } "$@"