C Tutorial: Playing with processes

Getting a parent process' process ID (PID)

Processes in Unix have a hierarchical relationship. When a process creates another process, that new process becomes a child of the process, which is known as its parent. If the parent process exits and the child is still running, the child gets inherited by the init process, the first process and everyone's ultimate parent.

You can get the parent's pid (process ID) for a process via the getppid system call.

Example

This is a small program that simply prints its process ID number and its parent's prcess ID number and then exits.

/* getppid: print a child's and its parent's process ID numbers */ /* Paul Krzyzanowski */ #include <stdlib.h> /* needed to define exit() */ #include <unistd.h> /* needed to define getpid() */ #include <stdio.h> /* needed for printf() */ int main(int argc, char **argv) { printf("my process ID is %d\n", getpid()); printf("my parent's process ID is %d\n", getppid()); exit(0); }

Download this file

Save this file by control-clicking or right clicking the download link and then saving it as getppid.c.

Compile this program via:

gcc -o getppid getppid.c

If you don't have gcc, You may need to substitute the gcc command with cc or another name of your compiler.

Run the program:

./getppid

Recommended

The Practice of Programming

 

The C Programming Language

 

The UNIX Programming Environment