makefileshgnu-makepid

Capture PID of command and use later inside makefile rule


I am struggling to find an elegant way of doing the following:

I want a makefile rule which:

Currently I have the following:

trace: 
    ./qemu/build/qemu-riscv64 -d plugin,nochain --trace "exec_tb" -plugin ./test_plugin.so ./test_qemu & export TRACE_PID=$$!; \
    echo Trace PID is $$TRACE_PID; \
    wait $$TRACE_PID; \ 
    python3 ./qemu/scripts/simpletrace.py ./qemu/build/trace/trace-events-all trace-$$TRACE_PID

But it doesn't seem to work. I see the "Trace PID is " but then get a command not found on line 1 which I think could be due to the stdout of qemu breaking things.

Is there a clean and elegant way to do this?


Solution

  • Captures this PID when qemu is invoked, ie ./qemu ... & echo $!

    The & causes your qemu to run in the background, but this is counter-productive because you want to wait for it to complete.

    The only real reason to capture the PID seems to be to compute the name of the trace file. If qemu supports it, the best approach would be to choose the name for the trace file yourself, and tell qemu to write there. Then you could just run qemu in the foreground (no wait), and analyze the file afterward. The mktemp command would serve to create a new file with a distinct name, if you need that.

    If you have no way to control the trace file name up front, then you could still do a little better (IMO) by keeping everything in the foreground, something like this:

    trace: 
            TRACE_PID=$$(/bin/sh -c 'echo $$$$; exec ./qemu/build/qemu-riscv64 -d plugin,nochain --trace "exec_tb" -plugin ./test_plugin.so ./test_qemu >qemu.out 2>&1'); \
            echo Trace PID is $$TRACE_PID; \
            python3 ./qemu/scripts/simpletrace.py ./qemu/build/trace/trace-events-all trace-$$TRACE_PID
    

    Notes: