Question

I want to use a temp directory that will be unique to this build. How can I get the pid of my make command in the Makefile?

I tried:

TEMPDIR = /tmp/myprog.$$$$

but this seems to store TEMPDIR as /tmp/myprog.$$ and then eval as a new pid for every command which refs this! How do I get one pid for all of them (I'd prefer the make pid, but anything unique will do).

Thanks in advance.

Was it helpful?

Solution

Try mktemp for creating unique temporary filenames. The -d option will create a directory instead of a file.

TEMPFILE := $(shell mktemp)
TEMPDIR := $(shell mktemp -d)

Note the colon. (Editor's note: This causes make to evaluate the function once and assign its value instead of re-evaluating the expression for every reference to $(TEMPDIR).)

OTHER TIPS

TEMPDIR := $(shell mktemp)

The problem is: every time you run make, it will create a temporary file. Regardless of you use it or not and regardless of the make target you use. That means: either you delete this file in every target or you they will not be deleted anytime.

I prefer to add the -u parameter:

TEMPDIR := $(shell mktemp -u)

This makes mktemp to create an unique filename without creating the file. Now you can create the file in the targets you need them. Of course there is a chance of a race conditions, where the file is used by another process before you create it. That is very unlikely, but do not use it in an elevated command, like make install.

make starts a new shell for each command it starts. Using bash (didn't check for other shells) echo $PPID gives the parent process ID (which is make).

all: subtarget 
        echo $$PPID
        echo $(shell echo $$PPID)

subtarget:
        echo $$PPID

Here is the answer to your question, which nobody seemed to want to give you:

TEMPDIR := /tmp/myprog.$(shell ps -o ppid $$$$)

Of course, this is not guaranteed to be unique.

You could use a date string. Unless you're kicking off multiple builds at the same time this should be pretty close.

Something like the following

pid_standin := $(shell date +%Y-%m-%d_%H-%M-%S)

file: 
    echo $(pid_standin)

$ Make
2010-10-04_21-01-58

Update: As noted in the comment if you set a variable with name = val syntax it is re-evaluated each time it's used. The := syntax sets it and doesn't re-evaluate the value, though using back-ticks `` seems to get around this somehow. You really want to use the $(shell CMD) construct for stuff like this.

Also, you can get your make pid like this.

PID := $(shell ps | tail -n 6 | head -n 1 | cut -f1 -d' ')

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top