0

I'm writing my own generic init script, I've taken strategies from here and there and come up with

trap 'kill $(jobs -p)' EXIT;
until $DAEMON $DAEMONOPTS  > /var/log/${NAME}.log 2>&1 & wait ; do
  echo "Server '$NAME' crashed with exit code $?.  Respawning.."  > /var/log/${NAME}.log 2>&1 & echo $!
  sleep 1
done

It kills the child process correctly on stop, it restart the service if dies etc.

Now I have to run that piece of code as a background job instead of directly in start)

The easy solution that works and I tested already would be to move this part in its own script and & it.

However I was wondering if there was a way to group these commands and send them in background, without having a second shell script to move around. Ideally I wanted to make this a gist so it should all be in a single file.

Is it even possible?

1 Answers1

1

In a shell script, you can group any sequence of commands in a subshell by using ( cmd; cmd ) and then put that subshell in the background with & as you already know; e.g. using your example codee:

(
  trap 'kill $(jobs -p)' EXIT;
  until $DAEMON $DAEMONOPTS  > /var/log/${NAME}.log 2>&1 & wait ; do
    echo "Server '$NAME' crashed with exit code $?.  Respawning.."  > /var/log/${NAME}.log 2>&1 & echo $!
    sleep 1
  done
) &

Though I have to say your until ... sleep notion to keep the daemon running is a bit odd. Not sure I would want the daemon to endless restart in the event of any failure. Perhaps at least check the exit code and only restart if it exited "uncleanly". Even then, if it dies because of a configuration file syntax error (assuming it has such a thing), that will also cause it to enter an endless restart loop.

  • thanks! well I pan to use this for a minecraft server I set up for my friends that leak memory and crashes every now and then. nothing I can do about it, and it is just to automate the routine of starting pageant, connecting, people can't play if I'm not available etc. – Lorenzo Boccaccia Sep 04 '15 at 17:25