-1

Lets say there are 3 java commands in my shell script:

java com.test.test1 &
java com.test.test2 &
java com.test.test3 

I need to get the PID of each and every command once it gets executed and store the PIDs in a file.

Note: I cant use $! as I'm using sleep in between.

Can you help me out?

Ronan Boiteau
  • 9,608
  • 6
  • 34
  • 56
  • This should answer your question: https://stackoverflow.com/questions/1908610/how-to-get-pid-of-background-process – Kabira K Nov 21 '17 at 23:57
  • There are many commands that can do the trick, but you can try `pgrep`, which doesn't need a lot of knowledge – Francisco Gallego Salido Nov 21 '17 at 23:57
  • 1
    What does using `sleep` have to do with gathering the pid from `$!`? Also, if you're using `sleep` in between, why do I not see it in your example code? Help us help you. Give us the whole picture. – ghoti Nov 22 '17 at 03:23

1 Answers1

1

You can use $! even if you're sleeping. Simply assign a variable between each invocation:

java com.test.test1 & pid1=$!
java com.test.test2 & pid2=$!
java com.test.test3 & pid3=$!

If you can't use this please include the whole code. Also, Greg's Wiki has a great article of how to do this.

l0b0
  • 55,365
  • 30
  • 138
  • 223