Linux - Topics
Orphan Process - When a parent process exits but the child process keeps running it will be orphaned. It is adopted by init or systemd and it’s PPID will become 1. This allows it to finish runninmg and clean up. Not usually harmful but can indicate a bug.
Zombie Process - A zombie process (or defunct process) is a child process that has completed execution but still has an entry in the process table because its parent hasn’t read its exit status.
- not adopted by init or systemd
- must wait until parent cleans them up
- caused because the parent process doesn’t call wait() or waitpid() to retreive exit status
- too many zombies can exhaust system resources
Example - creates zombie process:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main() {
pid_t pid = fork(); // Create a child process
if (pid > 0) {
// Parent process
printf("Parent process (PID: %d) sleeping...\n", getpid());
sleep(3000); // Parent does NOT wait for the child, causing a zombie
} else if (pid == 0) {
// Child process
printf("Child process (PID: %d) exiting...\n", getpid());
exit(0); // Child exits, but parent doesn't collect status
}
return 0;
}
As a fix, the parent can wait:
#include <sys/wait.h>
...
wait(0);
Ignore instead of using sig handlers:
struct sigaction sa;
sa.sa_handler = SIG_IGN; // Ignore SIGCHLD
sigaction(SIGCHLD, &sa, NULL);
Prevent zombie process:
- use wait
- or SIGCHLD signal handling:
Detect zombie processes ( Z in the STATE column means Zombie ):
ps aux | grep Z
ps -eo pid,ppid,state,cmd | grep defunct
How to Remove a Zombie Process?
kill -9 <parent_pid> # kill parent process
## OR
kill -SIGCHLD <parent_pid> # tell parent process to call wait()
Disk / FS
mkfs -v -t ext4 /dev/sde3
mkfs.ext4 /dev/sda4
mkfs.fat -F 32 /dev/sda1
mount /dev/sda4 /mnt
mkswap /dev/sda3
swapon /dev/sda3