php-pcntlHow to create a daemon using PCNTL fork in PHP?
Creating a daemon using PCNTL fork in PHP is a simple process. The following example code will create a daemon that will run in the background and output a message every 5 seconds:
<?php
declare(ticks = 1);
pcntl_signal(SIGCHLD, SIG_IGN);
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// parent process
exit();
} else {
// child process
while (true) {
echo "I'm a daemon\n";
sleep(5);
}
}
Output example
I'm a daemon
I'm a daemon
I'm a daemon
...
The code consists of the following parts:
-
declare(ticks = 1)
: This sets the number of ticks that PHP will wait before running signal handlers. -
pcntl_signal(SIGCHLD, SIG_IGN)
: This tells PHP to ignore the SIGCHLD signal, which is sent when a child process terminates. -
pcntl_fork()
: This creates a child process. -
if ($pid == -1)
: This checks if the fork failed. -
else if ($pid)
: This is the parent process. -
else
: This is the child process. -
while (true)
: This creates an infinite loop. -
echo "I'm a daemon\n"
: This outputs a message. -
sleep(5)
: This pauses the loop for 5 seconds.
Helpful links
More of Php Pcntl
- How to install PCNTL for PHP in Debian?
- How to use pcntl_wifexited in PHP?
- How to use pcntl_signal in PHP?
- How to check if PCNTL is enabled in PHP?
- How to use PCNTL alarm in PHP?
- How to prevent zombie processes with the PCNTL_FORK function in PHP?
- How to get the process ID with PHP PCNTL?
- How to use PCNTL signals in PHP?
- How to use pcntl_wait in PHP?
- How to use pcntl_fork in PHP?
See more codes...