Run PHP Script as Daemon Process
Running a PHP script as a long-running daemon process presents a specific set of challenges that differ significantly from standard web request handling. The core requirement is usually to keep a process alive, listen for external instructionsâperhaps via HTTP hooks, Unix sockets, or message queuesâand execute logic immediately upon arrival. While cron jobs are excellent for scheduled tasks, they introduce unacceptable latency when real-time responsiveness is required.
The traditional approach of spawning a long-running PHP CLI process with nohup or & often leads to "zombie" processes that consume memory without being garbage collected effectively. This is because the PHP runtime in CLI mode does not perform cleanup between requests as it does under the Apache mod_php environment, and standard daemonization techniques can leave file descriptors open or detach the process from its parent session incorrectly.
One tool historically associated with this problem is libslack/daemon. It was designed to manage daemon processes, but its lack of updates since around 2018 suggests that relying on it for modern deployments is risky. The underlying system calls and library dependencies may no longer align with current OS distributions or PHP versions, potentially leading to security vulnerabilities or stability issues. If you are currently considering using this tool, a prudent engineering decision is to evaluate whether the effort to maintain compatibility outweighs the benefits of a well-tested alternative.
For modern environments, especially those running Laravel or other robust frameworks, the industry standard has shifted away from manual daemonization scripts toward Process Managers like Supervisor (formerly supervisord) or systemd. These tools handle the lifecycle of the processâstarting it on boot, restarting it on crash, and managing PID filesâwithout you having to write complex shell scripts to detach from the terminal or manage signal handlers manually.
However, if your architecture requires a pure PHP solution without external dependencies like Supervisor, you can implement a robust daemon pattern directly within the script using POSIX signals. The critical logic involves checking for an already running instance at startup and handling termination signals gracefully. Below is a pattern that demonstrates how to structure a PHP script to act as a reliable daemon:
#!/usr/bin/env php
<?php
$pidFile = '/tmp/my_daemon.pid';
$logFile = '/var/log/my_daemon.log';
// Prevent multiple instances
if (file_exists($pidFile)) {
$currentPid = file_get_contents($pidFile);
if (posix_kill((int)$currentPid, 0) === false) {
die("Daemon is already running with PID {$currentPid}\n");
}
}
// Fork to background
if (posix_getppid() == 1) {
// Already a child process, do not fork again
$isForked = false;
} else {
$pid = posix_getpid();
file_put_contents($pidFile, (string)$pid);
// Fork once to background
$pid2 = @posix_fork() or die("Unable to fork: {$php_errormsg}\n");
if ($pid2) {
// Parent exits immediately
exit(0);
} else {
// Child continues
posix_setsid(); // Detach from controlling terminal
// Fork again to ensure no file descriptors are inherited (optional but recommended)
$pid3 = @posix_fork() or die("Unable to fork: {$php_errormsg}\n");
if ($pid3) {
exit(0);
}
$isForked = true;
}
}
// Log startup
file_put_contents($logFile, date('Y-m-d H:i:s') . " - Started\n", FILE_APPEND);
// Listen for instructions (example: checking stdin or socket)
while (true) {
// Implement your logic here to wait for signals or HTTP requests
// Ensure you handle SIGTERM and SIGINT to stop gracefully
sleep(1);
}
This implementation uses posix_setsid() to create a new session, detaching the process from the controlling terminal. It also performs a double-fork strategy to ensure the process does not inherit open file descriptors that could cause issues later, such as keeping standard input/output open unintentionally.
Despite these patterns, you must acknowledge the inherent limitations of PHP daemons. Memory management in PHP is optimized for short-lived scripts, not continuous execution. Variables defined at the global scope persist for the lifetime of the process, which can lead to memory leaks if not explicitly unset or if object graphs grow unbounded. Additionally, exception handling behaves differently; a fatal error in a daemon will kill the entire process rather than returning an HTTP 500 response, requiring your process manager to restart it automatically.
If you are building this on top of Laravel, note that the framework's service container and autoloading mechanisms expect a specific bootstrap flow that may not fit well inside a bare-bones daemon loop without modification. In such cases, utilizing a dedicated job worker or integrating with a message queue like RabbitMQ or Redis Pub/Sub is often more maintainable than trying to force Laravel into a raw CLI daemon mode.
Ultimately, the choice between writing a custom daemon script or adopting a process manager depends on your operational maturity and ecosystem. For production-grade reliability, leveraging existing infrastructure like systemd units provides better observability and control than maintaining custom PHP daemons manually.
