Skip to content
systemcoding.dev
Systems Programming

Get the current and parent PID with getpid and getppid

Read your own process ID and your parent's with getpid and getppid on Linux 6.12 and glibc 2.40. Neither call can fail, so there is nothing to check.

1 min read
Summarize in AI

Every process has an ID and a parent, and both are one call away. getpid() returns the caller's process ID and getppid() returns the ID of whoever created it, with the types and prototypes in <unistd.h>. The POSIX definition says neither function is ever reported as failing, so you can use the result inline without an error branch.

pids.cc
#include <stdio.h>
#include <unistd.h>

int main(void) {
    printf("pid=%d ppid=%d\n", (int)getpid(), (int)getppid());
    return 0;
}
Text
pid=48213 ppid=48190

The numbers will differ on every run. The parent here is usually your shell, which is why running the program twice gives the same ppid and a new pid.

The part the manual page buries is the parent. If the original parent exits first, the kernel reparents the child to PID 1, or to the nearest ancestor marked as a subreaper with prctl(PR_SET_CHILD_SUBREAPER), so getppid() can change under a running program. Do not cache it at startup to answer "is my parent still alive?". Compare it against the value you saw earlier instead, and treat a change as the parent having died. Inside a PID namespace the numbers are relative to that namespace, so a containerised process can legitimately see pid=1.

Taggedcposix
Share

More snippets

Systems Programming

Get the page size with sysconf(_SC_PAGESIZE)

Read the memory page size at run time with sysconf(_SC_PAGESIZE) instead of hard-coding 4096, which is wrong on arm64 kernels built with 16K or 64K pages.

1 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.