How To Find Process Id In Linux Using Command Line Tools

You Need to Track Down a Running Process

You’re staring at a terminal, trying to figure out why an application is frozen or consuming too much memory. Maybe you need to send a signal to restart a service, or perhaps a background script has gone rogue. The first step in taking control is identifying the exact process, and that requires its unique identifier: the Process ID, or PID.

In Linux, every running program gets assigned a numerical PID by the kernel. This number is the key to managing, monitoring, and terminating processes. Knowing how to find it quickly is a fundamental skill for troubleshooting, system administration, and development work.

This guide covers the essential command-line tools to locate any process ID, from the simplest commands for known applications to advanced techniques for filtering and real-time monitoring.

The Foundation: ps and grep

The most common method combines the `ps` (process status) command with `grep` for filtering. The `ps` command by itself shows a snapshot of current processes from your terminal session. To see all processes running on the system, you use `ps aux`.

Let’s say you’re looking for the PID of the NGINX web server. You would run:

ps aux | grep nginx

The output will show lines containing “nginx”. The second column is typically the PID. You might see something like:

root 1234 0.0 0.5 102340 21000 ? Ss 10:15 0:00 nginx: master process /usr/sbin/nginx
www-data 1235 0.0 0.3 102400 18000 ? S 10:15 0:00 nginx: worker process

Here, the master process has PID 1234 and a worker has PID 1235. The `grep` command itself will also appear in the list, which you can exclude by adding `grep -v grep`:

ps aux | grep nginx | grep -v grep

This gives you a cleaner list of just the target processes.

Understanding ps Output Columns

When you use `ps aux`, it’s helpful to know what you’re looking at. The key columns are:

USER: The owner of the process.
PID: The Process ID you need.
%CPU: CPU usage percentage.
%MEM: Memory usage percentage.
COMMAND: The command that started the process.

For a more focused view that shows only the PID and the command, you can use `ps -C` followed by the command name:

ps -C nginx -o pid,comm

This directly asks `ps` to show processes named “nginx” and output only the PID and command columns, eliminating the need for `grep`.

Specialized PID-Finding Commands

Linux offers tools built specifically for finding PIDs without parsing general output.

Using pidof for Simple Lookups

The `pidof` command is straightforward. Give it a program name, and it returns the PIDs of all running instances.

how to find pid linux

pidof nginx

This might return `1234 1235`, the PIDs separated by spaces. It’s perfect for scripts where you need to capture a PID programmatically. Be aware it matches the exact executable name. For a Java process like `java -jar myapp.jar`, `pidof java` would return the PID of all Java processes.

Using pgrep for Advanced Filtering

The `pgrep` command is a more powerful alternative. It searches the process table and prints PIDs matching given criteria. Its basic use is similar:

pgrep nginx

This will output just the PIDs, one per line. Where `pgrep` shines is its filtering options. You can find processes owned by a specific user:

pgrep -u www-data

Or find processes whose full command line matches a pattern (not just the executable name):

pgrep -f “myapp.jar”

The `-f` flag is crucial for finding scripts or Java applications where the process name is just “python” or “java”, but you need to identify a specific instance by its arguments.

Finding the PID of a Script You Just Launched

Sometimes you start a process in the background and immediately need its PID. The shell provides a special variable for this.

If you run a command with an ampersand to background it, the shell variable `$!` holds the PID of the most recent background job.

python3 long_script.py &
echo $!

This is invaluable in shell scripts where you need to store the PID for later management, like writing it to a PID file for a service.

Creating a PID File for Services

A common practice for daemons is to write their own PID to a file (like `/var/run/myservice.pid`). This allows management scripts to know exactly which process to signal for stop or reload commands. You can simulate this in a script:

#!/bin/bash
my_daemon &
daemon_pid=$!
echo $daemon_pid > /var/run/myservice.pid

Always ensure your cleanup script removes this PID file when the process stops.

When You Only Know the Port: lsof and ss

A frequent scenario is needing to find which process is listening on a specific network port, like port 80 or 443. For this, you use network utility tools.

how to find pid linux

Using lsof by Port Number

The `lsof` command (list open files) can show which process has a network port open. To find the PID using port 80:

sudo lsof -i :80

The `-i :80` flag filters for Internet files associated with port 80. The output will show the command name and its PID in the second column. You often need `sudo` to see processes owned by other users.

Using ss for a Faster Alternative

The `ss` command (socket statistics) is a modern replacement for `netstat` and is often faster. To find the PID of the process on port 80:

sudo ss -ltnp | grep :80

The flags are: `-l` for listening sockets, `-t` for TCP, `-n` for numeric ports, and `-p` to show process information. The output will include `pid=1234` where 1234 is the PID. This method is highly reliable and recommended on newer systems.

Interactive Process Discovery with top and htop

For a dynamic, real-time view of all processes and their PIDs, interactive tools are ideal.

The classic `top` command displays a continuously updated list of processes, sorted by CPU usage by default. The PID is clearly shown in the first column. You can press `k` while `top` is running to kill a process by entering its PID.

A more user-friendly alternative is `htop`. It provides a color-coded, vertical layout with easier navigation. You can scroll the list, search for process names with F3, and filter the display. Finding a PID here is as simple as visually scanning or using the search function.

Filtering Within htop

Press F4 in `htop` to enter a filter. Typing “nginx” will immediately filter the process list to show only lines containing that text, making the relevant PIDs instantly visible. This is often the quickest method for interactive troubleshooting on a local machine.

Finding PIDs for Systemd-Managed Services

On modern Linux distributions using systemd, services are managed by units. The `systemctl` command can directly give you the PID of a service.

systemctl status nginx.service

Look for the “Main PID” line in the output, which shows the primary process ID. For a more direct query, use:

systemctl show –property MainPID nginx.service

This will output `MainPID=1234`. This method is authoritative for services under systemd’s control and ensures you get the correct main process ID, not a helper or forked child.

What If the Process is Hiding or a Zombie?

Occasionally, you might encounter a “zombie” process (state Z). It has finished execution but still has an entry in the process table, often because its parent hasn’t read its exit status. Its PID will still appear in `ps` output, but you cannot kill it—it’s already dead. The cleanup must be handled by its parent process or a system reboot.

For processes that seem invisible to `ps` or `pgrep`, ensure you are using `sudo`. Some processes run under different names or are kernel threads. Kernel threads, often shown in square brackets like `[kworker]`, have PIDs but are part of the kernel and not managed like user applications.

how to find pid linux

Checking Process Hierarchy with pstree

Understanding parent-child relationships can help. The `pstree` command displays processes in a tree format, showing which process spawned which. This is useful to find all PIDs belonging to a single application group, like a web server and its worker processes.

pstree -p | grep -A 5 nginx

The `-p` flag includes PIDs in the output. This shows you the master PID and visually links it to its child worker PIDs.

Putting It Into Practice: A Common Troubleshooting Flow

Let’s walk through a real example. Your website is down, and you suspect the web server. First, find the PID:

pgrep -f nginx

If it returns nothing, NGINX isn’t running. If it returns a PID, check its resource usage with `top -p [PID]` or see if it’s listening on the correct port:

sudo ss -ltnp | grep [PID]

If you need to restart it gracefully, you would send a signal using the PID:

sudo kill -HUP [PID]

This HUP signal tells NGINX to reload its configuration without dropping connections.

Scripting for Reliability

In automation, always account for the possibility that a process isn’t running. A robust script snippet might look like:

APP_PID=$(pgrep -f “myapplication.jar”)
if [ -z “$APP_PID” ]; then
echo “Application is not running.”
exit 1
else
echo “Found application with PID: $APP_PID”
# Proceed with management tasks
fi

This prevents errors by checking if the PID variable is empty before using it.

Your Process Management Toolkit

Finding a PID is rarely the end goal. It’s the first step in process management. Once you have the PID, you can:

Monitor it in real-time with `top -p [PID]`.
Check the files it has open with `lsof -p [PID]`.
Send signals to control it: `kill -TERM [PID]` for a graceful stop, `kill -KILL [PID]` for a forced termination.
Trace its system calls with `strace -p [PID]` for deep debugging.

Start by mastering `pgrep -f` for precise searches and `sudo ss -ltnp` for port-based discovery. Combine these with the interactive view in `htop` for a complete picture of your system’s activity. Keep this command reference handy, and you’ll never lose track of a running process again.

Open a terminal and try finding the PID of your shell itself using `echo $$` or the PID of your current terminal with `pgrep -t $(tty)`. Practice builds the fluency that turns these commands into instinct.

Leave a Comment

close