0

Is there a shell tool that takes an arbitrary executable and makes a detectable, restartable background process out of it?

If I had to script this myself, I would use a $PIDFILE and something along the lines of...

if [ -f $PIDFILE ] && ps -p `cat $PIDFILE` &> /dev/null; then
    # Already running, kill, restart
else
    # Stale pidfile, start
fi

This sounds like there's a program that does this a thousand times better than anything I'd come up with, though. Is there?

If there isn't, what caveats and gotchas should I be aware of in implementing a script as the above?

3 Answers 3

0

On Debian systems there is start-stop-daemon. I recommend using that, and if you're not on Debian or Ubuntu, just copy that script from Debian and try it.

3
  • Can you give me an example user-space, shell session usage? I thought start-stop-daemon was meant for system services?
    – uʍop ǝpısdn
    Mar 22, 2013 at 11:17
  • I'll refer you to the man pages, since I don't have a system with start-stop-daemon in front of me. You'll need to pass a few arguments like --start --name foo --pidfile /tmp/foo.pid. There's no explicit "restart" feature, so for that you'll need to just do --stop --oknodo followed by --start. Mar 22, 2013 at 11:22
  • That's okay, knowing that the tool is suited for the job is enough. I'll do a bit of reading and get back here
    – uʍop ǝpısdn
    Mar 22, 2013 at 11:23
0

If you want to do it in a shell script, you can use subshells and do something like:

#!/bin/bash
(
while true; do
  echo "I'm process A"
  sleep 1
done
) &
(
while true; do
  echo "I'm process B"
  sleep 3
done
) &
wait
wait

The commands in parentheses are run in the background, because if the ampersand, and the wait commands, makes sure the parent scripts does not exit. It's possible save the pid of the subshells by saving $! after each subshell.

1
  • 1
    The second call to wait is unnecessary. The first one will not return until all background processes complete.
    – chepner
    Mar 22, 2013 at 12:59
0

Historically, such process monitoring was done by the init program. Today, init may have been replaced by your operating system by one of several proposed replacements: upstart, systemd, launchd (see http://en.wikipedia.org/wiki/Init for a longer list). Check which your OS uses to see how it creates and monitors long-running processes.

1
  • Thanks for your answer! I'm familiar with systemd and upstart, but I want to do this in user-space, within a regular shell session, no elevated priviledges. This is not a system service.
    – uʍop ǝpısdn
    Mar 22, 2013 at 14:21

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .