Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

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 &
PID=$!

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.

share|improve this question

1 Answer 1

up vote 2 down vote accepted

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.

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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