Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.


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?

share|improve this question
1  
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
2  
Please see Process Management. –  Dennis Williamson Jan 27 '11 at 10:44

2 Answers 2

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 "$!"

#!/bin/bash
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
#!/bin/bash
echo $$ > fooapp.pid
exec fooapp

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

share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.