I have a init.d script that starts a python socket server. Because I want this to run as a daemon, I use nohup to start it. I also want to redirect stdout and stderr to a log file. My problem is that I am also trying to capture the PID of the process to save to a file, which I can't seem to do.

# Start server
echo "Starting server."
nohup ${PROGDIR}/${PROGNAME} -l $IPADDR >>${LOGDIR}/${OUTLOG} 2>>${LOGDIR}/${OUTLOG} </dev/null &

This was able to capture the PID, but redirection did not work. (Was I redirecting nohup rather than the program?)

Next I tried something like:

nohup /bin/bash -c '...'

But I lost the PID. At this point, I seemed to be getting the PID of nohup /bin/bash -c. As I am not very familiar with shell scripts, I thought I would ask for help before I shoot myself in the foot.

So my question is, how can I capture the PID and redirect the server output to the logfile? I am on a debian (raspberry pi) and am writing an init script using rc-update.d.

1 Answer 1


If you're on a Debian variant, you have start-stop-daemon available, which does all this for you in a much cleaner way. In particular:

start-stop-daemon --make-pidfile --pidfile "$PIDFILE" --background \
    --no-close --exec "${PROGDIR}/${PROGNAME}" --start -- -l "$IPADDR" \
    >> "${LOGDIR}/${OUTLOG}" 2>> "${LOGDIR}/${OUTLOG}" </dev/null

should be pretty close to what you want. It puts the PID in a file instead of into a variable, but you can of course read it back out into a variable easily.

  • Looks like --no-close is not always available Feb 24, 2015 at 11:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.