Bash – Write a PID File Manually from Script

bash

How could I write a Bash-script that runs a long running program and stores the programs process id in a separate file?

I want something like

#!/bin/bash
exec long_running_tool
echo `ps af |grep "long_running_tool" |awk '$5 == "long_running_tool" {print $1}'` > pid_file

However doing exactly this would execute the ps after tool has finished.

Is there a way to get the process id of the process created?

Best Answer

You can easily run the process in the background with "&", then get the PID of the background process using "$!"

#!/bin/bash
long_running_tool &
echo $! > pid_file

Then, optionally, wait $! if you want the shell to block until the process completes execution.

Related Question