Senior LevelPHP 8+
How do you build multi-process CLI daemon workers using pcntl_fork() and POSIX process management?
❓ Interview Prompt: Explain process management with pcntl_fork(), POSIX process IDs, signal handling (pcntl_signal), zombie process reaping (pcntl_waitpid), and CLI daemons.
Long-running CLI queue workers can process jobs concurrently by spawning background worker processes using the PCNTL (Process Control) and POSIX extensions.
How Process Forking Works:
1
'pcntl_fork()': Clones the current master process into two identical running processes:
•
Returns Child PID (>0) to the Master Parent process.
•
Returns '0' to the new Child Worker process.
2
Signal Dispatching ('pcntl_signal'): Traps OS signals ('SIGTERM', 'SIGINT') for graceful shutdowns.
3
Reaping Zombie Processes ('pcntl_waitpid'): Master process reaps dead child worker processes to prevent Linux zombie process table leaks.
Code Implementation Example
php
<?php
// Forking worker child process in CLI daemon
$pid = pcntl_fork();
if ($pid === -1) {
die("Could not fork process!");
} else if ($pid === 0) {
// Child Worker Process Execution Loop
echo "[Child PID " . posix_getpid() . "] Processing background queue job...
";
sleep(2);
exit(0); // Exit child process cleanly!
} else {
// Master Parent Process
echo "[Master PID " . posix_getpid() . "] Spawned child worker PID {$pid}
";
pcntl_waitpid($pid, $status); // Reaps zombie child process!
}💡Forking background worker processes using pcntl_fork and reaping child processes with pcntl_waitpid.
🎯 Interview Key Takeaway
Use pcntl_fork() to spawn child processes, pcntl_signal() for graceful shutdown signals, and pcntl_waitpid() to reap zombie processes.
#pcntl#POSIX#Process Forking#CLI Daemons#Senior
Back to all PHP 8+ Questions→