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.

I'm wondering if there is a way to start a child process (not as a background process), and get its PID, possibly outputting it to a file.

I am starting a process in a bash script, namely java, and I'd like to be able to output the PID of this java process to a file, so I can use it in other scripts. The problem is that I'm not starting java as a background process, so I can't use $!. Any ideas onto how I would output the PID of the java process that I just started to a file?

Note that this java process is not going to be the only java process running on the system - if I get this working I'll be outputting the child process for different java processes to different files.

Only thing I've thought of is possible starting a background process that knows the PID of the current bash script, before starting java. Then using that background process to find the child process from the bash script. I wouldn't know exactly how to implement this though.

share|improve this question
add comment

1 Answer 1

up vote 1 down vote accepted

The best solution is probably to get the application itself to do it.  If that’s not an option, try wrapping the app in a shell script:

#!/bin/sh
echo My pid is $$.
exec /the/real/path/to/the/app

The key is the exec command, which causes the shell (the process that’s handling the script) to run that last program without forking, so it (the application) takes over process and inherits its PID.

share|improve this answer
    
This seems to be the perfect solution for my problem, thanks! –  DaboRoss Nov 21 '13 at 3:37
add comment

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.