getpid
- C course
- Advanced
- Lesson 10/83
- 5 min
Learn process IDs with getpid and getppid.
getpid and getppid
getpid() returns the ID (PID) of the calling process. getppid() returns the parent process ID. Both return a non-negative pid_t integer.
Every process has a unique PID. PID 1 is usually the init process. When a child is created with fork, getppid() gives the parent's PID. If the parent ends, the child is adopted by init and getppid() returns 1.
PID values
PIDs are assigned by the operating system and are always positive. You check the fork return to know if you are parent or child: 0 is child, positive is parent.
Using PIDs for comparison rather than printing them directly is safer; the value varies across systems. For example, printf("%d", getpid() > 0) always prints 1. This confirms the PID is positive.
Practice Check PIDs
Get identities with pid_t pid = getpid(); and pid_t ppid = getppid();. Print whether both are positive with printf("%d %d\n", pid > 0, ppid > 0);. The output must be 1 1.
Starter code
#include <stdio.h>
#include <unistd.h>
// Call getpid and getppid
// Print whether both are > 0
int main(void) {
return 0;
}Sample solution
#include <stdio.h>
#include <unistd.h>
int main(void) {
pid_t pid = getpid();
pid_t ppid = getppid();
printf("%d %d\n", pid > 0, ppid > 0);
return 0;
}Expected output
1 1
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What does getppid() return?
- Your own PID
- The parent's PID Correct answer
- 0
- The child's PID
Explanation: getppid returns the parent process PID.
2 Match PID concepts
| Term | Meaning |
|---|---|
getpid |
Own PID |
getppid |
Parent PID |
pid_t |
PID type |
fork |
Copies process |
3 getpid call
pid_t me = ____();
pid_t me = getpid();
Explanation: getpid returns the own process ID.