How to get pid of my make command in the Makefile?

和自甴很熟 提交于 2019-12-08 14:47:14

问题


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.


回答1:


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).)




回答2:


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.




回答3:


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



回答4:


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.




回答5:


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.




回答6:


Also, you can get your make pid like this.

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



来源:https://stackoverflow.com/questions/3860137/how-to-get-pid-of-my-make-command-in-the-makefile

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!