5

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?

3 Answers 3

18

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).

Sign up to request clarification or add additional context in comments.

Comments

3

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.

7 Comments

How to use $$ variable? Does it contain PID of last runned program or what?
Look at the example I gave. For the shell, it is its own PID.
in bash $! is the PID of the last background process.
@dldnh is this possible to receive the same in sh?
@Dirk but is it possible to know not the PID or the script, but the PID of the program runned by this script?
|
0

the top command in linux(Ubuntu) shows the memory usage of all running programs in linux with their pid. Kill pid can kill the process.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.