Johnny Utahh Johnny Utahh - 4 months ago 16
Python Question

How to get current Linux process ID (pid) from cmdline (in shell- and language-independent fashion)?

How to get one's current process ID (pid) from Linux cmdline (in shell- and language-independent fashion)? pidof(8) appears to have no option to get the calling-processes pid. bash of course has

$$
but for my generic usage, can't rely on a shell (bash or otherwise). And in some cases, can't write a script or compilable program (so bash, Python, C/C++, etc will not work).

Specific use case: get the pid of the running, Python-Fabric-based, remote ssh process (so that among other things I can copy/create files/dirs with unique filenames, as in
mkdir /tmp/mydir.$$
), where one may want to avoid assuming bash is running. If we can solve the Fabric-specific problem, that's helpful, but doesn't solve my long-term problem. For general-purpose usage in all future scenarios, just want a cmd that returns what
$$
delivers in bash.

Answer

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

Comments