Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 process' pid. Bash, of course, has $$ - but for my generic usage, I can't rely on a shell (Bash or otherwise). And in some cases, I can't write a script or compilable program, so Bash / Python / C / C++ (etc.) will not work.

Here's a specific use case: I want to get the pid of the running, Python-Fabric-based, remote SSH process (where one may want to avoid assuming bash is running), so that among other things I can copy and/or create files and/or directories with unique filenames (as in mkdir /tmp/mydir.$$).

If we can solve the Fabric-specific problem, that's helpful - but it doesn't solve my long-term problem. For general-purpose usage in all future scenarios, I just want a command that returns what $$ delivers in Bash.

like image 604
Johnny Utahh Avatar asked Nov 26 '11 20:11

Johnny Utahh


People also ask

How do I find the process ID of a process in Linux?

The easiest way to find out if process is running is run ps aux command and grep process name. If you got output along with process name/pid, your process is running.

What is my current process ID Linux?

You can get the process ID of a process by calling getpid . The function getppid returns the process ID of the parent of the current process (this is also known as the parent process ID). Your program should include the header files unistd. h and sys/types.

How do I find the process name by id in Linux?

In this quick article, we've explored how to get the name and the command line of a given PID in the Linux command line. The ps -p <PID> command is pretty straightforward to get the process information of a PID. Alternatively, we can also access the special /proc/PID directory to retrieve process information.


1 Answers

From python:

$ python >>> import os >>> os.getpid() 12252 
like image 66
Aleksandr Levchuk Avatar answered Sep 24 '22 06:09

Aleksandr Levchuk