DEV Community

Cover image for The PID You Saved Is Not the Process: Practical pidfd on Linux
Lyra
Lyra

Posted on

The PID You Saved Is Not the Process: Practical pidfd on Linux

The PID You Saved Is Not the Process: Practical pidfd on Linux

A restart helper reads /run/api.pid, runs kill -0 to confirm the service is alive, then sends SIGTERM. It works for months. Then one night the service exits between those two calls, the kernel hands its PID to an unrelated process, and the helper kills the wrong thing. There was no syntax bug. It asked the wrong question.

A PID is an index into a table the kernel reuses. kill -0 answers "does this number currently belong to a process I am allowed to signal?" It cannot answer "is this still the process I started?"

Linux has a better handle for that: a pidfd, a file descriptor that refers to the process itself rather than to its number. It is small, boring, and fixes a class of bugs that shell scripts cannot fix with more careful checking.

The short version:

  • A pidfd is a real file descriptor. You poll it to learn that the process exited, waitid() to collect its status, and pidfd_send_signal() to signal it without a PID lookup.
  • It cannot be tricked by PID reuse. After the target is gone, operations fail with ESRCH instead of hitting a stranger.
  • Its edges are sharper than they look: read() fails, POLLHUP only appears after reaping, waitid() only works for your own children, and mixing it with subprocess can silently turn a failure into exit code 0.

Everything below was measured on Debian 13 (kernel 6.12.118+deb13-amd64, systemd 257.13-1~deb13u1, Python 3.14.6) unless marked as documentation history.

The three answers kill(2) can give

With sig = 0, no signal is delivered; only the existence and permission checks run. That check returns exactly three outcomes:

Result errno What it means
0 - Some process currently holds that number, and you may signal it
-1 EPERM The process exists, but it is not yours to signal
-1 ESRCH No such process - and yes, a zombie that has not been reaped still counts as existing

The permission rule is real: the sender needs CAP_KILL in the target's user namespace, or matching real/saved-set UIDs, with SIGCONT getting a session-based exception. So EPERM is not a failure to find the process; it is proof that something is there.

The race is documented in kill(2) itself: "the sender may accidentally send a signal to the wrong process if the originally intended target process has terminated and its PID has been recycled."

How likely is reuse? On this host /proc/sys/kernel/pid_max is 4194304, shipped by systemd in /usr/lib/sysctl.d/50-pid-max.conf. A large ceiling makes recycling less frequent, not impossible. Fork-heavy builds, container churn, and a long-lived PID file from a previous boot all shrink the odds you care about.

What a pidfd is, and what it is not

pidfd_open(2) arrived in Linux 5.3. It returns a descriptor that refers to the task named by pid:

int syscall(SYS_pidfd_open, pid_t pid, unsigned int flags);
Enter fullscreen mode Exit fullscreen mode

There is no glibc wrapper, so C callers use syscall(2); Python exposes os.pidfd_open(). The descriptor is close-on-exec. It is not a path into /proc, and on this kernel it does not even look like one:

$ readlink /proc/self/fd/5
anon_inode:[pidfd]

$ cat /proc/self/fdinfo/5
pos:    0
flags:  02000002
mnt_id: 4
ino:    22279
Pid:    21979
NSpid:  21979
Enter fullscreen mode Exit fullscreen mode

The name is an implementation detail. Pid and NSpid in fdinfo are the useful part when you are staring at a descriptor table and wondering what is holding a process reference.

Three ways to get a handle:

  1. pidfd_open(pid, 0) for a process that already exists.
  2. open("/proc/<pid>", O_RDONLY) - which works, but the pidfd_open(2) man page is explicit that this descriptor is not pollable and cannot be used with waitid().
  3. clone(2)/clone3(2) with CLONE_PIDFD, when you are creating the child and want the handle atomically.

That third option matters more than it sounds, because the zombie guarantee for pidfd_open() is conditional. The man page lists three requirements: SIGCHLD must not be set to SIG_IGN, SA_NOCLDWAIT must not have been set, and the zombie must not have been reaped elsewhere. If any of those fails, the page says to create the child with CLONE_PIDFD instead. A supervisor that installs SIG_IGN for SIGCHLD and then calls pidfd_open() is setting itself up for ESRCH.

Flags and errors are small enough to memorize:

  • PIDFD_NONBLOCK (Linux 5.10) makes waitid() return EAGAIN instead of blocking while the target is alive.
  • PIDFD_THREAD (Linux 6.9) makes the descriptor refer to one thread instead of the thread-group leader.
  • ESRCH means the PID does not exist; EINVAL means the PID or flags are invalid; ENODEV means the kernel's anonymous-inode filesystem is unavailable; EMFILE/ENFILE are the usual descriptor limits.

The kernel history is worth keeping straight when you support older hosts:

Feature Since
pidfd_send_signal() Linux 5.1
pidfd_open() Linux 5.3
waitid() with P_PIDFD Linux 5.4
pidfd_getfd() Linux 5.6
PIDFD_NONBLOCK Linux 5.10
PIDFD_THREAD, PIDFD_SIGNAL_* flags Linux 6.9

Waiting for exit: poll, do not read

A pidfd becomes readable when the task becomes a zombie. It produces a hangup when the task is reaped. It is not a file: read() fails with EINVAL, and the man page says so plainly ("nothing can be read from the file descriptor").

Measured with a child that sleeps and then exits 42:

alive:  poll=0 revents=0
exit:   poll=1 revents=0x1     # POLLIN
waitid: si_pid=22118 si_status=42 si_code=1   # CLD_EXITED
reaped: poll=1 revents=0x11    # POLLIN|POLLHUP
Enter fullscreen mode Exit fullscreen mode

That sequence is the whole contract, and it has three consequences people miss:

  • Readability is not process death. Without PIDFD_THREAD, the descriptor becomes readable only when the last thread in the thread group exits. A process with one stuck thread is alive as far as this handle is concerned.
  • Hangup means reaped. POLLHUP is tied to the reaping, not the death. If you never reap, you get POLLIN forever.
  • Only the parent reaps. A pidfd for an unrelated process normally reports POLLIN when that process dies and never reports POLLHUP, because you are not the one who can collect it.

Thread-level handles work, but they need the flag. In C, PIDFD_THREAD is literally O_EXCL in the uapi header (/usr/include/linux/pidfd.h), which is why raw-syscall examples pass 0x80 on x86-64. Opening the native thread ID with that flag gave a descriptor that stayed quiet while the thread ran, then reported revents=0x11 when the thread exited while the process was still alive - exactly the distinction a process-level pidfd cannot make. Python 3.14 has no os.PIDFD_THREAD constant, so this path needs ctypes or C.

Reaping: waitid(P_PIDFD) is for your children only

Linux 5.4 added P_PIDFD to waitid(). It gives you the exit status without a second PID lookup:

siginfo_t si = {0};
if (waitid(P_PIDFD, pidfd, &si, WEXITED) == -1)
    perror("waitid");
/* si.si_pid, si.si_code, si.si_status */
Enter fullscreen mode Exit fullscreen mode

Measured on the same host:

  • Child exiting 5: si_code=1 (CLD_EXITED), si_status=5.
  • Child killed by SIGTERM: si_code=2 (CLD_KILLED), si_status=15.
  • Child that ignores SIGTERM and is then killed: si_code=2, si_status=9.

The constraints are where supervisors get hurt:

  • Not your child, no status. waitid(P_PIDFD, ...) on a pidfd for your own parent returned ECHILD (errno 10). The same happens if SIGCHLD is ignored.
  • Nonblocking plus alive means EAGAIN. With PIDFD_NONBLOCK, waitid() on a running child returned EAGAIN (errno 11) rather than blocking.
  • WNOWAIT peeks. It reports the state change without reaping, so you can inspect before deciding.

The trap: two reapers, one exit status

subprocess.Popen has its own reaper. If you call waitid(P_PIDFD) first, Popen's later waitpid() gets ECHILD. CPython's Popen._try_wait() handles that case by setting sts = 0, because it assumes the child was already reaped elsewhere. The result is not an error; it is a successful-looking exit code of 0.

Measured: a child that exited 3 produced si_status=3 from waitid(), and then p.wait() returned 0. A CI step would have passed. This is the kind of bug that survives review because every individual call looks correct.

The rule is simple: pick one owner of the exit status. If you use subprocess, poll the pidfd and let Popen reap. If you use waitid(P_PIDFD), spawn with os.fork() + os.execvp() and reap it yourself.

Signaling without a lookup

pidfd_send_signal(2) (Linux 5.1) sends a signal to the process the descriptor refers to. The man page's framing is the reason the syscall exists: traditional interfaces "specify the target process via a process ID (PID), with the result that the sender may accidentally send a signal to the wrong process if the originally intended target process has terminated and its PID has been recycled."

After the target is reaped, pidfd_send_signal() fails with ESRCH. It does not retarget the recycled number. Measured after reaping the child above:

signal after reap: rc=-1 errno=3 (No such process)
Enter fullscreen mode Exit fullscreen mode

Details that matter in production:

  • If info is non-NULL, it must follow the rt_sigqueueinfo(2) rules; with NULL the kernel fills in SI_USER semantics like kill(2).
  • The caller must be in the same PID namespace as the target, or an ancestor of it. Otherwise EINVAL.
  • Permission failures are EPERM, not ESRCH - the target exists, you just may not signal it.
  • The PIDFD_SIGNAL_THREAD, PIDFD_SIGNAL_THREAD_GROUP and PIDFD_SIGNAL_PROCESS_GROUP flags arrived in Linux 6.9. They change the scope of the signal when the descriptor refers to a thread or a leader; they do not turn one pidfd into an arbitrary process-group handle. Signaling -pgid still needs kill(2) and still has its own race.

There is a second useful primitive: pidfd_getfd(2) (Linux 5.6) duplicates a descriptor from the target process, gated by a PTRACE_MODE_ATTACH_REALCREDS check. That is how a debugging or migration tool can inherit an open socket without cooperation from the target, and why it is privileged in practice.

Complete C example

This is the program I compiled with gcc -O2 -Wall on Debian 13. It forks a child, opens a pidfd, polls it, reaps with waitid(), and then proves the descriptor does not signal anything after reaping.

#define _GNU_SOURCE
#include <errno.h>
#include <poll.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/syscall.h>
#include <sys/wait.h>
#include <unistd.h>

static int pidfd_open(pid_t pid, unsigned int flags) {
    return syscall(SYS_pidfd_open, pid, flags);
}

static int pidfd_send_signal(int pidfd, int sig, siginfo_t *info,
                             unsigned int flags) {
    return syscall(SYS_pidfd_send_signal, pidfd, sig, info, flags);
}

int main(void) {
    pid_t pid = fork();
    if (pid == 0) {            /* child */
        sleep(2);
        _exit(42);
    }

    int fd = pidfd_open(pid, 0);
    if (fd < 0) { perror("pidfd_open"); return 1; }

    struct pollfd pfd = { .fd = fd, .events = POLLIN };
    int n = poll(&pfd, 1, 0);
    printf("alive:  poll=%d revents=%#x\n", n, pfd.revents);

    n = poll(&pfd, 1, 5000);   /* returns when the child is a zombie */
    printf("exit:   poll=%d revents=%#x\n", n, pfd.revents);

    siginfo_t si = {0};
    if (waitid(P_PIDFD, fd, &si, WEXITED) == -1) {
        perror("waitid");
    }
    printf("waitid: si_pid=%d si_status=%d si_code=%d\n",
           si.si_pid, si.si_status, si.si_code);

    n = poll(&pfd, 1, 0);      /* now reaped: POLLIN|POLLHUP */
    printf("reaped: poll=%d revents=%#x\n", n, pfd.revents);

    int rc = pidfd_send_signal(fd, 0, NULL, 0);
    printf("signal after reap: rc=%d errno=%d (%s)\n",
           rc, errno, strerror(errno));

    close(fd);
    return 0;
}
Enter fullscreen mode Exit fullscreen mode

Output on kernel 6.12.118:

alive:  poll=0 revents=0
exit:   poll=1 revents=0x1
waitid: si_pid=22118 si_status=42 si_code=1
reaped: poll=1 revents=0x11
signal after reap: rc=-1 errno=3 (No such process)
Enter fullscreen mode Exit fullscreen mode

A supervisor that cannot signal the wrong process

The same logic in Python, with a deadline and a two-stage kill. It uses fork() + execvp() so that the process which calls waitid() is the one that owns the status.

#!/usr/bin/env python3
"""Run one child under a deadline using a pidfd as the process handle."""
import os
import select
import signal
import time


def spawn(argv):
    pid = os.fork()
    if pid == 0:                      # child
        try:
            os.execvp(argv[0], argv)
        except OSError as exc:
            os.write(2, f"exec {argv[0]}: {exc}\n".encode())
        os._exit(127)                 # only reached if exec failed
    return pid                        # parent


def supervise(argv, timeout=10.0, grace=3.0):
    pid = spawn(argv)
    pidfd = os.pidfd_open(pid)        # stable handle, close-on-exec
    poller = select.poll()
    poller.register(pidfd, select.POLLIN)

    deadline = time.monotonic() + timeout
    while not poller.poll(0):         # [] while the child is alive
        left = deadline - time.monotonic()
        if left <= 0:
            signal.pidfd_send_signal(pidfd, signal.SIGTERM)
            stop = time.monotonic() + grace
            while not poller.poll(0) and time.monotonic() < stop:
                time.sleep(0.05)
            if not poller.poll(0):
                signal.pidfd_send_signal(pidfd, signal.SIGKILL)
            break
        poller.poll(max(1, int(left * 1000)))

    info = os.waitid(os.P_PIDFD, pidfd, os.WEXITED)   # reaps the child
    os.close(pidfd)
    return info


if __name__ == "__main__":
    info = supervise(["/bin/sh", "-c", "exit 5"], timeout=2)
    print(f"si_pid={info.si_pid} si_code={info.si_code} si_status={info.si_status}")
    info = supervise(["/bin/sh", "-c", "sleep 30"], timeout=0.3, grace=1)
    print(f"si_pid={info.si_pid} si_code={info.si_code} si_status={info.si_status}")
    info = supervise(["/bin/sh", "-c", "trap '' TERM; sleep 30"],
                     timeout=0.3, grace=0.5)
    print(f"si_pid={info.si_pid} si_code={info.si_code} si_status={info.si_status}")
Enter fullscreen mode Exit fullscreen mode

Output:

si_pid=22148 si_code=1 si_status=5     # clean exit
si_pid=22149 si_code=2 si_status=15    # SIGTERM
si_pid=22151 si_code=2 si_status=9     # ignored SIGTERM, got SIGKILL
Enter fullscreen mode Exit fullscreen mode

Note what is absent: no os.kill(pid, ...), no waitpid(pid), no window where a recycled number can be targeted. The descriptor is the identity.

When you have to persist identity

A pidfd is a runtime handle. It cannot be written to a pid file, cannot survive a reboot, and cannot be sent to another host. If a second process must verify "same process as before", persist more than the number:

def identity(pid):
    with open(f"/proc/{pid}/stat", "rb") as fh:
        raw = fh.read().decode()
    fields = raw.rsplit(")", 1)[1].split()
    return {
        "pid": pid,
        "starttime": fields[19],   # field 22: clock ticks since boot
        "boot_id": open("/proc/sys/kernel/random/boot_id").read().strip(),
    }
Enter fullscreen mode Exit fullscreen mode

Parse from the right of the last ) because comm can contain spaces and parentheses; proc_pid_stat(5) defines field 22 as starttime. Measured on this host: the same process reported 22753353 across reads, a newly spawned process reported 22753373. Add boot_id because starttime restarts at boot; comparing it across boots is meaningless.

If the process is managed by systemd, do not build this by hand. systemd 255 moved most internal process tracking to pidfds ("Most of the internal process tracking is being changed to use PIDFDs instead of PIDs when the kernel supports it", NEWS), and its D-Bus API can resolve a unit from a pidfd GetUnitByPIDFD(). systemctl already owns the handle.

The traps, in one table

Symptom Cause Fix
read() returns EINVAL A pidfd is not readable Use poll()/epoll() for state, waitid() for status
waitid() returns ECHILD Not your child, or SIGCHLD is ignored Only reap children; use pidfd_open() + poll() otherwise
waitid() returns EAGAIN PIDFD_NONBLOCK and the target is alive Expected; wait for readability first
pidfd_send_signal() returns ESRCH Target already reaped Correct behavior; the handle is dead, not retargeted
Exit status silently becomes 0 waitid(P_PIDFD) consumed it before subprocess reaped One reaper only
No POLLHUP ever The process was never reaped, or you are not its parent HUP follows reaping, not death
Thread exit not reported Process-level pidfd waits for the last thread Use PIDFD_THREAD (Linux 6.9)
pidfd_open() returns ESRCH right after spawn Child was already reaped, or SIGCHLD was SIG_IGN Create with CLONE_PIDFD, or stop ignoring SIGCHLD
EMFILE under load One descriptor per tracked process Close handles promptly; budget against RLIMIT_NOFILE

Checklist before you ship it

  • Use pidfds wherever you currently do "check PID, then signal PID". The check is the bug.
  • Poll for exit; do not read. Reap with waitid(P_PIDFD) only if the process is your child.
  • Never mix waitid(P_PIDFD) with a library that also reaps the same child.
  • Keep the descriptor, not the number, for the lifetime of the supervision.
  • For cross-restart identity, store boot_id + pid + starttime, and still treat the result as advisory.
  • Remember the kernel floor: pidfd_open() needs 5.3, P_PIDFD needs 5.4, thread handles need 6.9. Fall back to kill(2) only when you must support older kernels, and document the race you are accepting.

PIDs were designed to be cheap and reusable. That is the right design for scheduling and the wrong design for identity. A pidfd costs one descriptor and removes an entire category of "how did the deploy script kill the database" incidents.

References

Top comments (1)

Collapse
 
userxnom profile image
Abdullah Naseer •

The opening race is the part that makes this piece stick: kill -0 says a number is alive, then the service exits, the PID is reused, and SIGTERM lands on a stranger. Framing a PID as an index the kernel reuses, not an identity, explains why the check-then-signal pattern is the bug itself. The measured details are what sell it — pid_max 4194304 on this host, a child exiting 42 giving poll revents 0x1 and waitid si_status 42, and the subprocess trap where a child exiting 3 is reaped by waitid first and then p.wait() returns 0. That last one would pass CI while hiding a real failure. The POLLIN versus POLLHUP distinction is also easy to get wrong: readable means zombie, hangup means reaped, and an unrelated process may never give you POLLHUP at all. When you are supervising a service that is not your child, do you poll the pidfd and let its own parent reap, or is there another pattern you reach for first?