Skip to content Skip to sidebar Skip to footer

How To Get The Current Linux Process ID From The Command Line A In Shell-agnostic, Language-agnostic Way

How does one get their current process ID (pid) from the Linux command line in a shell-agnostic, language-agnostic way? pidof(8) appears to have no option to get the calling proces

Solution 1:

From python:

$ python
>>> import os
>>> os.getpid()
12252

Solution 2:

Hope this is portable enough, it relies on the PPID being the fourth field of /proc/[pid]/stat:

cut -d ' ' -f 4 /proc/self/stat

It assumes a Linux with the right shape of /proc, that the layout of /proc/[pid]/stat won't be incompatibly different from whatever Debian 6.0.1 has, that cut is a separate executable and not a shell builtin, and that cut doesn't spawn subprocesses.

As an alternative, you can get field 6 instead of field 4 to get the PID of the "session leader". Interactive shells apparently set themselves to be session leaders, and this id should remain the same across pipes and subshell invocations:

$ echo $(echo $( cut -f 6 -d ' ' /proc/self/stat ) )
23755

$ echo $(echo $( cut -f 4 -d ' ' /proc/self/stat ) )
24027

$ echo $$
23755 

That said, this introduces a dependency on the behaviour of the running shell - it has to set the session id only when it's the one whose PID you actually want. Obviously, this also won't work in scripts if you want the PID of the shell executing the script, and not the interactive one.


Solution 3:

Great answers + comments here and here. Thx all. Combining both into one answer, providing two options with tradeoffs in POSIX-shell-required vs no-POSIX-shell-required contexts:

  1. POSIX shell available: use $$
  2. General cmdline: employ cut -d ' ' -f 4 /proc/self/stat

Example session with both methods (along with other proposed, non-working methods) shown here.

(Not sure how pertinent/useful it is to be so concerned with being shell independent, but have simply experienced many times the "run system call without shell" constraint that now seek shell-independent options whenever possible.)


Solution 4:

If you have access to the proc filesystem, then /proc/self is a symlink to the current /proc/$pid. You could read the pid out of, for instance, the first column of /proc/self/stat.

If you are in python, you could use os.getpid().


Solution 5:

Fewer characters and guaranteed to work:

sh -c 'echo $PPID'

Post a Comment for "How To Get The Current Linux Process ID From The Command Line A In Shell-agnostic, Language-agnostic Way"