saving PID of spawned process within a Makefile

Chris Camacho picture Chris Camacho · Apr 29, 2014 · Viewed 7.3k times · Source

I currently have a Makefile rule thus:

start:
    ./start.sh

which starts a very simple server needed as part of the build process. I have another rule for stopping the server:

stop:
    kill `cat bin/server.PID`

here is the start.sh script:

#!/bin/bash
cd bin
python server.py &
echo $! > server.PID

NB server.py must be run from within the bin directory

I'd like to implement the functionality of start.sh within the start rule, I've tried numerous things but can't seem to get the PID.

Answer

reinierpost picture reinierpost · Apr 29, 2014

I don't understand where you're getting stuck. What's wrong with

start:
    cd bin && { python server.py & echo $$! > server.PID; }

?

You can also make the pidfile a target and dependency:

start: server.PID

server.PID:
    cd bin && { python server.py & echo $$! > $@; }

stop: server.PID
    kill `cat $<` && rm $<

.PHONY: start stop