Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

is there any way to know the pid of a launched program?

Tags:

bash

if I launch a bash script as a child, I can pass its own pid to the parent by using $$.

Is there any way to find the pid of a program that I launch from a script in background like:

ping x.x.x.x &

what's the pid of that ping ?

(I just hope I expressed my self correctly ... my English is not the best)

PS. I'm looking for a simple and clean solution, I can imagine something like:

ping -t10000 -W10 x.x.x.x &
then
ps ax | grep 'ping -t10000 -W10 x.x.x.x'$

but is too complicated, also even that I used switches to personalize it is not clean, it may catch another processes in the system

like image 689
THESorcerer Avatar asked May 24 '12 11:05

THESorcerer


2 Answers

The variable $! has the PID of the last background process you started.

like image 181
Alex L Avatar answered Oct 15 '22 03:10

Alex L


Use this: $! right after executing the command whose PID you want. It means, though that you need to use an ampersand (&) after the command, to start it in background. E.g.:

my_command & CMDPID=$!
echo "$CMDPID"
like image 36
0xC0000022L Avatar answered Oct 15 '22 05:10

0xC0000022L