Course contentsShow
← C
Lesson 1069 of 1,21915. Systems ProgrammingFree lesson

Parent processes and getppid()

Parent processes and getppid()

What you'll learn: How to identify the "creator" of a process using the unique Process ID of its parent.

The Family Tree of Software

In Linux and Unix-like systems, processes don’t just appear out of nowhere. Every process is created by another process. This creates a hierarchy similar to a family tree. When you run a program from your terminal, the terminal (the parent) spawns your program (the child).

Just as every process has its own ID (PID), it also keeps track of who started it. This "creator" is known as the Parent Process, and its identification number is the PPID (Parent Process ID).

Meeting the Parent with getppid()

To find out who the parent is, we use the getppid() function. Think of it like a child asking, "Who is my guardian?" This function takes no arguments and returns the PID of the process that birthed the current one.

This is incredibly useful for system stability. If a child process needs to report an error or send a signal back to the "boss" that started it, it needs the PPID to know where to send that message.

Seeing it in Action

Include the unistd.h header to access process functions. In the following example, we print both the current process's identity and its parent's identity.

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

int main() {
    // Get the current process ID
    pid_t my_id = getpid();
    
    // Get the parent process ID
    pid_t parent_id = getppid();

    printf("I am process %d.\n", my_id);
    printf("My parent is process %d.\n", parent_id);

    return 0;
}

If you run this program in a standard terminal, parent_id will typically be the PID of your shell (like bash or zsh). The terminal sits there waiting for your program to finish, acting as the watchful parent.

The "Init" Ancestor

What happens if the parent finishes its work and exits before the child does? The child becomes an "orphan." In modern systems, the system adopts these orphans, usually reassigning them to a special system process (like systemd or init) which has a PID of 1. Every single process on your computer can eventually be traced back to this original ancestor.

Key takeaway

Every process is born from another; use getppid() to retrieve the unique ID of the process that started the current one.