0

I currently am starting a Java process, and am trying to get its PID using $!, and writing that to a file. The problem is, when I start the Java process, it goes into its own "console". (I'm not sure what this is called).

I'm not able to write this $! to a file until I have stopped the process and exited out of its "console", where the PID is then useless.

How would I go about starting the Java process, and getting its PID without ending it? I am using echo $! > pidfile.pid to write the PID of the Java process to a file.

hexacyanide
  • 88,222
  • 31
  • 159
  • 162
  • Do you have a `&` at the end of the line that starts the Java process? Without showing some code all we can do is guess. – Dennis Williamson Jun 25 '12 at 05:12
  • Are you running java in the background so the calling script keeps running while java is starting up? – John3136 Jun 25 '12 at 05:13
  • do it like (java -jar jarname&); pid=$! – pizza Jun 25 '12 at 07:05
  • Right -- What @pizza gave returns the PID of the containing shell, not that of the backgrounded process. What Dennis gave is the usual Right Thing, so the place to start is diagnosing why it doesn't appear to work for you. – Charles Duffy Jun 26 '12 at 00:38
  • Is the syntax you gave in your example _exactly_ what you're doing? Does it give any error messages when you try it? – Charles Duffy Jun 26 '12 at 00:40
  • Are you trying to daemonize your java process? If you are, there are existing packages to help you (for example, see http://stackoverflow.com/questions/407016 and http://stackoverflow.com/questions/534648) – phs Jun 26 '12 at 01:20
  • @CharlesDuffy That is the exact command. It shows a pid, which is incorrect, and fails to start the jarfile. – hexacyanide Jun 26 '12 at 01:31
  • @hexacyanide If that exact command is giving you an incorrect pid, the Java program you're starting is likely spawning a child and exiting -- in which case you *can't* detect the PID from the parent. Try another approach, such as opening a lockfile during the spawn and using fuser to track down processes with that file open after the fact. – Charles Duffy Jun 26 '12 at 01:52

1 Answers1

1

Write small Java wrapper starter java.sh (for example):

#!/bin/bash
pidfile=/some/path/pidfile.pid
echo $$ > $pidfile
exec java $@

In short shell script writes out its PID and then replaces itself with java process with all parameters that you pass to shell script. Then simply replace java with java.sh in your scripts... and of course you can pass pidfile through exported variable.

nudzo
  • 17,166
  • 2
  • 19
  • 19