Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to run a program and know its PID in Linux?

Tags:

linux

shell

pid

How to run a program and know its PID in Linux?

If I have several shells running each other, will they all have separate PIDs?

like image 254
Suzan Cioc Avatar asked Mar 27 '12 13:03

Suzan Cioc


2 Answers

Greg's wiki to the rescue:

  • $! is the PID of the last backgrounded process.
  • kill -0 $PID checks whether $PID is still running. Only use this for processes started by the current process or its descendants, otherwise the PID could have been recycled.
  • wait waits for all children to exit before continuing.

Actually, just read the link - It's all there (and more).

$$ is the PID of the current shell.

And yes, each shell will have its own PID (unless it's some homebrewed shell which doesn't fork to create a "new" shell).

like image 96
l0b0 Avatar answered Sep 29 '22 18:09

l0b0


1) There is a variable for that, often $$:

edd@max:~$ echo $$                  # shell itself
20559
edd@max:~$ bash -c 'echo $$'        # new shell with different PID
19284
edd@max:~$ bash -c 'echo $$'        # dito
19382
edd@max:~$ 

2) Yes they do, the OS / kernel does that for you.

like image 42
Dirk Eddelbuettel Avatar answered Sep 29 '22 16:09

Dirk Eddelbuettel