-
Notifications
You must be signed in to change notification settings - Fork 23
Create a daemon with Qpm Process
In multitasking computer operating systems, a daemon is a program that runs as a background process, rather than being under the direct control of an interactive user.
The daemon which is programed in PHP always run in CLI mode. It’s very different from the CGI mode. In CGI mode, a life cycle of a script is just a HTTP request, it’s a short time. But the daemons, they often run and have to run a long time.
They often run in a infinite loop like bellows.
<?php
while(true) {
file_put_contents('foo.log', date('Y-m-d H:i:s')."\n", FILE_APPEND);
sleep(10);
};
?>
In that example, a time info would be appended to foo.log per every 10 seconds. In the CGI mode, the process would be affected by the max time limitation, that is set in php.ini or the configuration of HTTP server. But in the CLI mode, process would keep running until a termination signal is received.
In a Unix environment, the parent process of a daemon is often, but not always, the init process. A daemon is usually either created by a process forking a child process and then immediately exiting, thus causing init to adopt the child process, or by the init process directly launching the daemon. In addition, a daemon launched by forking and exiting typically must perform other operations, such as dissociating the process from any controlling terminal (tty).
A common solution contains following steps:
- Start the process.
- Fork a child process.
- Let the child run in the background. (posix_setsid())
- The parent exits, but the child leaves alone in the background.
A implementor with QPM looks like following(or see the example script in daemon.php).
use Comos\Qpm\Process\Process;
//define the main working process.
function work() {
while(true) {
file_put_contents(__FILE__.'.log', date('Y-m-d H:i:s')."\n", FILE_APPEND);
sleep(10);
};
}
//Start a child by forking
Process::fork(
function() {
//The child send itself to the background
Process::current()->toBackground();
work();
}
);
文档首页 ##教程
- 安装和使用QPM
- 使用Process创建daemon程序
- 使用Supervisor创建健壮的多进程程序
- 使用Supervisor实现基于队列的并行任务处理程序
- 使用Pid 防止进程重复启动
- 使用日志,接入第三方日志
##参考
##旧版本
##Guides
- Getting Started
- Create a daemon with Qpm/Process
- Create Robust Multiprocess Programs with Supervisor
- Create a Queue-based Parallel Task Processing Program with Supervisor
##References