Super User is a question and answer site for computer enthusiasts and power users. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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

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?

share|improve this question
Your sample code won't work because exec doesn't fork, so the shell process is replaced by the long_running_tool process. Consequently, exec never returns and the following line is never reached. See help exec, execve(2). – e-t172 Jan 27 '11 at 10:04
@e-t172 thank you for pointing out. I delete 'exec' then. – DerMike Jan 27 '11 at 10:24
Please see Process Management. – Dennis Williamson Jan 27 '11 at 10:44
up vote 7 down vote accepted

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

long_running_tool &
echo $! > pid_file

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

share|improve this answer
I actually tried the '&' thing, but didn't think of fg. Thank you :-) – DerMike Jan 27 '11 at 10:13
UPDATE: when I use the fg I get 'fg: 21: job (null) not created under job control' and the script does not block. Sorry. – DerMike Jan 27 '11 at 10:23
"wait $!" should have a similar effect to fg that I can confirm does in fact, work in a script. I should probably have checked that before posting. >.> my bad. – Jeremy Sturdivant Jan 27 '11 at 10:29
echo $$ >
exec fooapp

As mentioned earlier, exec replaces bash with the specified program, retaining the PID.

share|improve this answer

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .