Website Vidya
Linux & ServersStep-by-Step Guide

pidof Command in Linux: Find Process IDs by Program Name

Learn pidof command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

RR
Rajesh RayLead Systems Educator
Published:
10 min read
PDF Cheat Sheet
pidof Command in Linux: Find Process IDs by Program Name
AI Executive SummaryWebsiteVidya AI

10 min read

Learn pidof command in linux with syntax, essential flags, practical terminal examples, real-world sysadmin workflows, security tips, and troubleshooting.

Key Highlights
  • What pidof Does and When to Use It
  • Availability and Installation Across Linux Distributions
  • Command Syntax, Arguments, and Exit Status Codes
Grounded in full engineering runbookWebsiteVidya AI Engine

Interactive Builder for this Guide

Build your custom find syntax (pidof Command in Linux: Find Process IDs by Program Name)

Generated POSIX Command
find /var/log -maxdepth 4 -type f -name '*.log' -size +50M -mtime +14 -exec ls -lh {} +
Searches inside /var/log for matching entries matching *.log.
Flag-by-Flag Breakdown
/var/logStarting root directory to traverse
-maxdepth 4Descend at most 4 directory levels
-type fMatch only regular files
-name '*.log'Filter filename glob (case-sensitive)
-size +50MMatch files larger than 50M
-mtime +14Modified more than 14 days ago
-exec ls -lh {} +Batch matched paths cleanly into ls -lh

When managing services or writing health-check scripts, the pidof command in linux provides the fastest and safest way to translate an exact binary name—such as nginx, sshd, or postgres—into its active Process IDs (PIDs). While administrators used to chain ps aux | grep name | grep -v grep | awk '{print $2}', that pipeline is fragile and prone to partial-name collisions.

Originally distributed as part of sysvinit-tools (where it was implemented as a mode of killall5) and now maintained inside procps-ng on modern Linux distributions, pidof walks the /proc virtual filesystem and outputs all matching PIDs on a single line separated by spaces (or a custom delimiter).

Because pidof requires an exact match on the program name rather than a substring regular expression, running pidof ssh will not accidentally match sshd or ssh-agent. This strict matching behavior, combined with flags for single-PID retrieval (-s), script discovery (-x), and PID exclusion (-o), makes pidof a staple utility in init scripts and cron wrappers.

Advertisement
pidof Command in Linux: Find Process IDs by Program Name — syntax, flags, and practical terminal workflow diagram
pidof Command in Linux: Find Process IDs by Program Name — command syntax, key options, and production workflow reference.

What pidof Does and When to Use It

When pidof runs, it iterates over every numeric directory in /proc/[0-9]* and inspects three kernel pseudo-files for each process: /proc/PID/stat (for the task state and short command name), /proc/PID/cmdline (for the null-delimited argument vector argv[0]), and the symbolic link /proc/PID/exe (which points to the actual binary inode on disk).

If you pass an unqualified program name like pidof nginx, the utility compares the basename of argv[0] and the resolved target of /proc/PID/exe against nginx. If you pass an absolute path like pidof /usr/sbin/nginx, it resolves the inode and device ID via stat(2) to ensure only processes running that exact file on disk are returned. By default, pidof prints matched PIDs in descending numerical order (newest processes first) separated by a single space.

Under the hood, pidof gathers runtime telemetry or dispatches control signals by reading virtual filesystems mounted at /proc and /sys, or by communicating with PID 1 (systemd) over D-Bus. Using flags such as -s, -x, -o, -c turns raw process and service tables into actionable diagnostics during incident response.

Availability and Installation Across Linux Distributions

The pidof utility is packaged in procps across mainstream Linux distributions. It is pre-installed on standard Ubuntu, Debian, RHEL, Rocky Linux, AlmaLinux, Fedora, and Arch Linux systems, while minimal container images may require manual installation:

Advertisement

Before running administrative tasks or automation scripts, verify whether pidof is installed and inspect which binary path and version your shell resolves:

type -a pidof
pidof --version 2>/dev/null || man -f pidof

# Illustrative output (reviewed against documentation)
pidof is /usr/bin/pidof
pidof (procps)
# Debian / Ubuntu
sudo apt-get update && sudo apt-get install -y procps

# RHEL / Rocky / AlmaLinux / Fedora
sudo dnf install -y procps-ng

# Arch Linux
sudo pacman -S --noconfirm procps-ng

# Alpine Linux
sudo apk add --no-cache procps-ng

Command Syntax, Arguments, and Exit Status Codes

pidof [OPTIONS] program_name [program_name...]

The syntax pidof [OPTIONS] program [program...] accepts one or more program names or full file paths. If at least one matching PID is found for any specified program, pidof writes the list of PIDs to standard output and terminates with exit status 0. If no processes match, it produces no output and exits with status 1.

Understanding how pidof handles interpreted scripts is essential: when a bash or python script runs via a shebang line (such as #!/usr/bin/env bash), the kernel records the interpreter (bash) as the executable name and places the script path in argv[1]. Therefore, you must pass the -x flag when using pidof to locate running shell scripts.

  • 0 — Successful execution with no runtime or permission errors.
  • 1 — Operational failure, unmatched condition, or permission restriction.
  • 2 — Invalid command-line option or malformed syntax.

Important Options and Flags Reference

Option / FlagLong Form / ArgumentTechnical Behavior and Purpose
-s--single-shotInstructs pidof to return only a single PID (the most recently spawned matching process) instead of all matching PIDs.
-x--scripts-tooAlso matches shells or interpreters running named scripts whose filename appears in the command-line arguments.
-o--omit-pid PIDExcludes one or more specified PIDs (or the special keyword %PPID for the calling shell's parent) from the output.
-c--check-rootOnly returns processes that share the exact same root directory (/proc/PID/root) as the pidof process itself (requires root).
-d--separator SEPUses the specified character or string SEP as the delimiter between output PIDs instead of the default space.
-q--quietQuiet mode; suppresses all standard output and only sets the exit code (0 if found, 1 if not found).
-w--with-workersIncludes kernel worker threads that do not have user-space command-line arguments in the search results.
-z--zombie-tooIncludes processes currently stuck in uninterruptible sleep (D) or zombie (Z) states when scanning /proc.

Two flags turn pidof into a surgical scripting tool: -d (custom separator) and -o %PPID (omit parent PID). For example, utilities like top -p and pgrep expect comma-separated PID lists rather than space-separated lists; running pidof -d, nginx formats the output as 29411,29410,1104 without needing tr or sed.

Advertisement

Similarly, when a bash script named backup.sh runs pidof -x backup.sh to check whether another instance of itself is already running, it will detect its own PID unless you exclude the current script using pidof -x -o %PPID backup.sh.

When combining short flags on the command line, POSIX and GNU utilities allow clustering boolean flags behind a single hyphen, provided any option taking an argument appears last. In automated shell scripts, using long-form GNU options where portable makes self-documenting code that is easier to audit during peer review.

Practical Basic and Advanced Usage Examples

1. Find All Process IDs of a Running Service

Pass the exact binary name of a service to pidof to retrieve all active master and worker PIDs on a single line.

pidof nginx

# Illustrative output (reviewed against documentation)
29411 29410 1104

pidof scans /proc and prints all matching nginx PIDs in reverse chronological order (highest/newest worker PIDs first, followed by the master PID 1104).

2. Return Only a Single Process ID with -s

When attaching a debugger like strace or gdb that accepts a single PID target, pass -s (--single-shot) to retrieve only one PID.

pidof -s nginx

# Illustrative output (reviewed against documentation)
29411

The -s option stops after finding the first matching process in /proc and outputs a single integer.

3. Format Output with Comma Separators Using -d for top or ps

Use -d ',' to output comma-delimited PIDs that can be passed directly into ps -p or top -p.

pidof -d ',' sshd
ps -f -p "$(pidof -d ',' sshd)"

# Illustrative output (reviewed against documentation)
14220,14198,892
UID          PID    PPID  C STIME TTY          TIME CMD
root         892       1  0 Oct20 ?        00:00:01 sshd: /usr/sbin/sshd -D [listener] 0 of 10-100 startups
root       14198     892  0 18:40 ?        00:00:00 sshd: admin [priv]
admin      14220   14198  0 18:40 ?        00:00:00 sshd: admin@pts/0

Replacing the default space delimiter with a comma makes pidof directly compatible with tools that parse comma-separated PID lists.

4. Find the PID of a Running Shell Script with -x

Because shell scripts execute inside a bash or sh interpreter process, pass -x so pidof inspects argv[1] for the script name.

pidof -x log-shipper.sh

# Illustrative output (reviewed against documentation)
30115

Without -x, pidof would only see /bin/bash as the binary name and return nothing. With -x, it matches the script filename passed to the interpreter.

5. Exclude Specific PIDs or the Calling Script with -o

Omit a known master PID or use the special %PPID token to exclude the calling shell script when checking for duplicate instances.

pidof -o 1104 nginx

# Illustrative output (reviewed against documentation)
29411 29410

Passing -o 1104 filters the master process out of the returned list so you can inspect or signal only the worker processes.

6. Restrict PID Discovery to Host Processes Only (Ignore Containers) with -c

On a Docker or Kubernetes host running containerized nginx instances, use sudo pidof -c so only processes sharing the host root filesystem (/) are returned.

# Without -c, returns both host and container nginx PIDs:
pidof nginx
# With sudo and -c, returns only host-level nginx PIDs:
sudo pidof -c nginx

# Illustrative output (reviewed against documentation)
44120 44119 29411 29410 1104
29411 29410 1104

The -c flag compares /proc/PID/root against the caller's root directory, preventing host maintenance scripts from accidentally signaling processes running inside isolated container namespaces.

Real-World Workflows, Pipelines, and Shell Automation

Prevent Concurrent Cron Script Execution (Singleton Check)

Use pidof -x -o %PPID at the top of a scheduled maintenance script to abort immediately if a previous run is still active.

#!/usr/bin/env bash
set -euo pipefail

SCRIPT_NAME=$(basename "$0")
OTHER_PIDS=$(pidof -x -o %PPID -o $$ "$SCRIPT_NAME" || true)

if [ -n "$OTHER_PIDS" ]; then
  echo "[WARN] $SCRIPT_NAME is already running under PID(s): $OTHER_PIDS. Exiting." >&2
  exit 0
fi

echo "[INFO] Starting exclusive run of $SCRIPT_NAME (PID $$)..."
sleep 2
echo "[INFO] Job completed."

# Illustrative output (reviewed against documentation)
[INFO] Starting exclusive run of nightly-sync.sh (PID 31890)...
[INFO] Job completed.

Because pidof spawns in a subshell ($(...)), omitting both %PPID (the parent script shell) and $$ ensures only genuinely separate concurrent instances are flagged.

Silent Service Liveness Probe in Monitoring Scripts

Combine pidof -q with conditional execution to verify that critical daemons are alive and log an alert if no PID is found.

#!/usr/bin/env bash
set -euo pipefail

for daemon in sshd cron rsyslogd; do
  if pidof -q "$daemon"; then
    echo "[OK] $daemon is running (PIDs: $(pidof -d ',' "$daemon"))"
  else
    echo "[CRITICAL] $daemon is NOT running!" >&2
  fi
done

# Illustrative output (reviewed against documentation)
[OK] sshd is running (PIDs: 14220,14198,892)
[OK] cron is running (PIDs: 741)
[OK] rsyslogd is running (PIDs: 755)

The -q flag suppresses stdout during the if-check and relies purely on the 0 or 1 exit code for clean conditional branching.

Pipelines, Redirection, Quoting, and Shell Expansion

When embedding pidof inside shell pipelines (|), conditional chains (&& and ||), or command substitutions ($(...)), the calling shell performs tilde expansion, variable interpolation, and globbing before invoking the binary. Always wrap paths, patterns, and variables in quotes so whitespace and wildcard characters (*, ?) are not expanded prematurely, and use set -euo pipefail in unattended scripts.

Permissions, Security Implications, and Safe Execution

When run by an unprivileged user, pidof can read /proc/PID/stat and /proc/PID/cmdline (unless the kernel is mounted with hidepid=2 on /proc), but it cannot dereference /proc/PID/exe or /proc/PID/root for processes owned by root or other users. Consequently, matching by full path (pidof /usr/sbin/sshd) or using -c requires sudo privileges.

On hardened production servers where /proc is mounted with hidepid=invisible (or hidepid=2), unprivileged users can only discover PIDs belonging to their own effective UID.

GNU/Linux, BSD, and BusyBox Implementation Differences

The pidof utility is standard across Linux distributions via procps-ng (or BusyBox on Alpine Linux), though BusyBox's minimal pidof supports only basic flags (-s and -o) and omits -c, -d, and -q.

On FreeBSD and macOS, pidof is not installed by default. For cross-platform POSIX/BSD scripts, use pgrep -x program_name as a portable equivalent.

Troubleshooting Common Errors and Diagnostics

pidof returns empty output (exit code 1) for a running Python or Node.js script

Root Cause: The process was launched as 'python3 app.py' or 'node server.js', so the binary name in /proc/PID/exe is python3 or node rather than the script name.

Resolution: Use pidof -x <script_name> if invoked via a shebang, or use pgrep -f 'python3 app.py' to match the full argument vector.

pidof -x app.py || pgrep -f "python3 .*app.py"

pidof /usr/sbin/sshd returns nothing when run as a normal user

Root Cause: Matching by full filesystem path requires reading the /proc/PID/exe symlink, which the kernel restricts to the process owner or root (CAP_SYS_PTRACE).

Resolution: Either pass the basename ('pidof sshd') or elevate privileges with sudo when specifying a full binary path.

sudo pidof /usr/sbin/sshd

pidof matches Zombie (Z) or Uninterruptible Disk Sleep (D) processes unexpectedly

Root Cause: In older sysvinit-tools versions of pidof, processes in D or Z states were sometimes skipped by default unless configured; in modern procps-ng, behavior is controlled via -z.

Resolution: Inspect the state of returned PIDs with ps -o pid,stat,comm -p $(pidof -d, <name>) before sending signals.

ps -o pid,stat,comm -p "$(pidof -d ',' nginx)"

Authoritative References and Official Documentation

Frequently Asked Questions

Quick answers to common questions and configurations

4 FAQs
pidof requires an exact match on the program name and prints all PIDs on a single space-separated line. pgrep matches partial regular expressions by default, prints one PID per line, and offers rich filters for user (-u), group (-G), terminal (-t), and parent process (-P).
Pass the -s (--single-shot) option, such as pidof -s nginx. It returns only the first matching PID found in /proc.
Shell scripts are executed by an interpreter binary (/bin/bash or /bin/sh). You must include the -x flag (pidof -x myscript.sh) so pidof inspects the script filename argument passed to the shell.
pidof returns exit status 0 if at least one matching process ID is found, and exit status 1 if no matching process is running.
RR
Written byVerified Author

Rajesh Ray

I’m Rajesh Rai, a full-stack developer, Linux administrator, and technology enthusiast passionate about making complex technology easier to understand and use.

SPAM-FREE MODERATED DISCOURSE

Join the Conversation & Perspective

Have thoughts, counterpoints, or reflections on this story? Engage directly with fellow readers and editorial contributors.

AT
MP
JV
+2

No comments on this guide yet. Be the first to share your thoughts or ask a question!

Recommended Reading10 Guides

Related Technical Guides

Tested runbooks, server administration walkthroughs, and troubleshooting guides

Featured Infrastructure PartnerUp to 75% OFF + 3 Months Free

Supercharge Your Linux & Cloud Workloads with Hostinger

Deploy high-speed NVMe KVM VPS, Docker containers, and LiteSpeed-accelerated WordPress servers in under 60 seconds with full root access, dedicated IPv4, and 24/7 technical support.

Pure NVMe SSD StorageFull Root Access & SSHFree Domain & Unlimited SSL99.9% Uptime SLA
Plans from$2.99/mo
Claim Hostinger DealAffiliate link • Special discount applied at checkout