I am trying to do some process control in a script (bash). For this reason I output the process group id of the current process to a file.
ps ax -o '%p %r'|perl -ne 'if ($_ =~ /\s*$$\s*(\d+)/) { print "$1"; exit; }' > $pgidfile
nohup $JAVA_HOME/bin/java -cp somejar.jar some.java.Program & > /dev/null 2>&1
I have also tried:
ps ax -o '%p %r'|awk '/'"$$"' [0-9]+/ {print $2}' > $pgidfile
nohup $JAVA_HOME/bin/java -cp somejar.jar some.java.Program & > /dev/null 2>&1
However in both these cases, the file (in $pgidfile) seems to be empty. (Although on certain rare occasions it does seem to have the correct value.) Also, just running the commands(to output the process group id – option 1 or option 2 above) themselves on the commandline seem to do the right thing.
It would be great if someone could suggest a solution to the above problem or answer either (or both) of the following questions:
1) What is the suggested way to get a process’s group id in a shell or perl script?
2) Does running a command under nohup change the output redirection of previous/subsequent commands that aren’t related to the command executed with nohup?
An improvement to your current approach would be to do an exact field match on the PID you care about. Any unanchored regex technique (such as your original post) runs the risk of matching the wrong thing. If $$ happens to be 123, you’ll match
psoutput lines for PIDs 1123, 1234, etc.Now,
awkandperlare both very good at processing field delimited input (see perl’s-aswitch), but you don’t need to do that, since you can limitpsto just the process you care about:Find out how your
pscan be told to omit headers, and you can removetailfrom that pipeline.No. Something else is amiss in your scenario.