Capturing the PID of a background process started

2019-02-10 02:39发布

问题:

I have a Makefile that starts a Django web server. I would like the server to be started in the background, with the PID saved to a file.

My recipe looks like this:

run: venv
    @"${PYTHON}" "${APP}/manage.py" runserver 80

Intuitively, to background the process and capture the PID, I'd have to do something like this:

run: venv
    @"${PYTHON}" "${APP}/manage.py" runserver 80 & ; echo "$$!" > "${LOGDIR}/django.pid"

This doesn't work, though. The sub-shell that 'make' uses (/bin/sh in my case) works when you use:

<command> &

...to background a process, and works when use:

<command> ; <command>

(or <command> && <command>, etc...) to chain commands. However, when I try to background the first process and chain a second one, I get the following error:

/bin/sh: -c: line 0: syntax error near unexpected token `;'

What is the best way to background a process and capture the PID in a Makefile?

Thanks
- B

回答1:

Just leave a single ampersand, without a semicolon after it:

run: venv
    @"${PYTHON}" "${APP}/manage.py" runserver 80 & echo "$$!" > "${LOGDIR}/django.pid"

Ampersand acts as command separator in the same way as a semicolon:

<command> & <command>


回答2:

If Make gives you too much trouble, you can always have the target launch an sh script; in that script, launch the process, background, and then output the pid to a file.