Implement a simple non-daemon service program that can be started by an external supervisor (which will background it and record its PID) and that runs until it is killed. Place your solution in /app/.
Requirements
Create an executable file at /app/service (script or binary).
/app/service must:
Run in the foreground (do not fork/daemonize).
Run indefinitely until it receives a termination signal from the OS (SIGTERM). When terminated it should exit cleanly (exit code 0).
Not create or manage any PID files itself.
Accept no required command-line arguments and produce no required output (writing to stdout/stderr is allowed). It must not background itself.
Make sure the file is executable (shebang + chmod +x if a script).
Notes to implementer (do not hard-code external supervisor behavior)
An external controller will start the service in the background and use the process id to manage/stop it. Your service must stay alive until killed by that controller (or a kill signal). Implementing a signal handler to exit on SIGTERM will make shutdown deterministic and clean.
Keep the implementation minimal: a small shell or Python script that traps SIGTERM and sleeps/loops is sufficient.
Tests
The following test script will be used to verify your solution:
bash
#!/bin/sh
# start/stop service and create pid file for a non-daemon app
# service command
service_cmd="/opt/service/service"
# pid file location
service_pid="/var/run/service.pid"
if [ $# -eq 1 -a "$1" = "start" ]; then
if [ -f "$service_pid" ]; then
kill -0 $(cat $service_pid) 2>/dev/null # check pid
if [ $? -eq 0 ]; then
exit 2; # process is running, exit
else
unlink $service_pid # process is not running
# remove stale pid file
fi
fi
# start service in background and store process pid
$service_cmd >/dev/null &
echo $! > $service_pid
elif [ $# -eq 1 -a "$1" = "stop" -a -f "$service_pid" ]; then
kill -0 $(cat $service_pid) 2>/dev/null # check pid
if [ $? -eq 0 ]; then
kill $(cat $service_pid) # kill process if it is running
fi
unlink $service_pid
fi