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

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
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:

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

You must log in to answer this question.

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