Keywords: PHP Daemon | Linux Background Process | nohup Command | System Service Management | Process Control
Abstract: This article provides a comprehensive exploration of various technical approaches for running PHP scripts as daemon processes in Linux environments. Focusing on the nohup command as the core solution, it delves into implementation principles, operational procedures, and advantages/disadvantages. The article systematically introduces modern service management tools like Upstart and systemd, while also examining the technical details of implementing native daemons using pcntl and posix extensions. Through comparative analysis of different solutions' applicability, it offers developers complete technical reference and best practice recommendations.
Fundamental Concepts of Daemon Processes and PHP Application Scenarios
In Unix/Linux systems, a daemon process is a special type of process that runs in the background, independent of controlling terminals, and performs specific tasks over extended periods. Although PHP is not designed as the primary language for daemon processes, developers still need to run PHP scripts as daemons in certain scenarios, particularly when real-time response to instructions is required rather than scheduled execution.
Implementing PHP Daemons Using nohup Command
The most straightforward and efficient solution involves using the Unix nohup command combined with background execution symbols. The implementation is as follows:
nohup php myscript.php &
In this command, nohup ensures the process continues running after user logout, while the & symbol places the process in the background. This approach's advantage lies in its simplicity and ease of use, enabling quick deployment without complex configuration.
For process management, status can be checked using ps aux | grep php, and the process can be terminated with the kill command:
kill <process_id>
Although this method lacks advanced features like automatic restart, it provides sufficient control for basic daemon requirements.
Service Management Using Upstart
For scenarios requiring system-level management, Ubuntu's Upstart offers a more comprehensive solution. First, create the configuration file /etc/init/myphpworker.conf:
description "My PHP Worker"
author "Developer"
start on startup
stop on shutdown
respawn
respawn limit 20 5
script
[ $(exec /usr/bin/php -f /path/to/script.php) = 'ERROR' ] && ( stop; exit 1; )
end script
After configuration, management can be performed using standard service commands:
sudo service myphpworker start
sudo service myphpworker stop
sudo service myphpworker status
Upstart automatically handles process startup, shutdown, and monitoring, ensuring service recovery after system reboots.
Modern Service Management with systemd
In modern Linux distributions using systemd, more granular control can be achieved by creating service unit files. Create /etc/systemd/system/myphpdaemon.service:
[Unit]
Description=PHP Daemon Service
Requires=mysqld.service
After=mysqld.service
[Service]
Type=simple
ExecStart=/usr/bin/php -f /srv/www/daemon.php
Restart=on-failure
RestartSec=30s
[Install]
WantedBy=multi-user.target
Service management commands include:
systemctl start myphpdaemon
systemctl enable myphpdaemon
systemctl status myphpdaemon
systemd provides rich feature options such as dependency management, resource limits, and log integration, making it suitable for production deployments.
Implementing Native Daemons Using PHP Extensions
Through pcntl and posix extensions, standard daemon behavior can be implemented at the PHP code level:
<?php
// Set file creation mask
umask(0);
// First fork
$pid = pcntl_fork();
if ($pid < 0) {
exit("Fork failed");
} elseif ($pid) {
exit(); // Parent process exits
}
// Create new session
posix_setsid();
// Second fork
$pid = pcntl_fork();
if ($pid < 0) {
exit("Second fork failed");
} elseif ($pid) {
exit();
}
// Change working directory
chdir('/');
// Close standard file descriptors
fclose(STDIN);
fcose(STDOUT);
fclose(STDERR);
// Main loop
while (true) {
// Business logic processing
process_tasks();
// Memory management
if (PHP_SAPI == "cli") {
gc_collect_cycles();
}
usleep(100000); // 100ms interval
}
function process_tasks() {
// Specific business logic implementation
}
This approach offers maximum flexibility but requires developers to handle complex issues like signal processing and error recovery.
Technical Solution Comparison and Selection Recommendations
Different technical solutions have distinct advantages: the nohup approach suits rapid prototyping and simple tasks; Upstart and systemd fit production environments requiring system integration and automated management; native PHP implementation works for special scenarios needing fine-grained control. Selection should consider deployment environment, maintenance requirements, and team technology stack.
Memory Management and Best Practices
PHP daemon processes require particular attention to memory management. Regular calls to gc_collect_cycles() for forced garbage collection are recommended to prevent memory leaks. For long-running processes, graceful restart mechanisms should be implemented to periodically reload configurations and clean resources.
In actual deployments, combining monitoring tools like Supervisord for process management is advised to ensure service reliability and maintainability. Additionally, comprehensive logging and error handling mechanisms are crucial for production environments.