0

I have a shell script that runs a Java process p1 and also there's a non-Java process p2 that takes input from p1.

How can I get process id of p1?

I have a shell script that works unpredictably (sometimes it works, sometimes it doesn't). I have browsed the net but none of the answers seem perfect.

My script:

nohup sh -c "exec java p1 | p2 2>&1" &
$pid=`echo $!`
my_pid=exec ps -eo "%p %c %P" | awk -v p=$pid 'p==$3{print $1 $2}' | grep java | sed -e 's/java//'

echo "my_pid $my_pid"
mkjeldsen
  • 2,053
  • 3
  • 23
  • 28
S Kr
  • 1,831
  • 2
  • 25
  • 50
  • 1
    Why do you need the process ID if your other process just needs to read from the first? Can you just pipe the output of `p1` into `p2`? – Attila May 19 '12 at 18:37
  • possible duplicate of [How to get the PID of a process in a pipeline](http://stackoverflow.com/questions/3345460/how-to-get-the-pid-of-a-process-in-a-pipeline) – Tom Anderson May 19 '12 at 19:30
  • @TomAnderson Yes i have seen that. – S Kr May 20 '12 at 04:43
  • @TomAnderson Yes i have seen that. The recommended solution of named pipes doesn't work for me, my process p1 is a long running process and that can be terminated only later by reading the pid file and calling "kill pid". Using the named pipe causes my command to get stuck. I was not able to run `job -p` – S Kr May 20 '12 at 04:50
  • You might have trouble with `jobs -p` because of the `exec` you're doing. Not sure. However, there are other answers there which don't involved named pipes or `jobs`. – Tom Anderson May 20 '12 at 09:35
  • a simple error in the script above seem like $pid=`echo $!`. That is, to assign a value to a variable, use: "var=..." rather than "$var=..". Also why backticking, why not simply "pid=$!" ? – inger Nov 10 '13 at 00:16

1 Answers1

2

This is a simplified version of mmd's answer from the question i linked to:

{ java p1 & echo $! >&2; } | p2 2>&1 &

This prints the PID of p1 on standard error. You also get a message from the shell telling you that the echo command has finished, but you can ignore that.

Community
  • 1
  • 1
Tom Anderson
  • 46,189
  • 17
  • 92
  • 133
  • Ok i figured out my problem, after starting the parent process , i was calling my script directly. At that time the child processes were not spawn. I have added a sleep nohup sh -c "exec java p1 | p2 2>&1" & $pid=`echo $!` sleep 5 my_pid=exec ps -eo "%p %c %P" | awk -v p=$pid 'p==$3{print $1 $2}' | grep java | sed -e 's/java//' echo "my_pid $my_pid" How can i use wait instead of sleep? – S Kr May 21 '12 at 07:43
  • I can't read all that in a comment. Either add it to the question, or, better, ask a new question. Even better, ask it on http://unix.stackexchange.com/ , which is specialised in this sort of stuff. – Tom Anderson May 21 '12 at 16:13