PHP守护进程开发指南:原理、场景与安全实践
1. 什么是守护进程
守护进程是指那些脱离终端控制、在系统后台持续运行的进程。其脱离终端的主要目的是防止执行过程中的信息输出到任何终端界面,同时避免被终端产生的信号或信息所中断。
常见的守护进程实例包括 Apache、Nginx 和 MySQL 等服务软件。
2. 为什么开发守护进程
许多应用程序以无终端和无UI交互的服务形式存在,它们通常通过 TCP/UDP Socket、UNIX Socket 或 FIFO 等方式与其他程序进行通信。这类程序一旦启动便进入后台等待,直到满足特定条件才开始处理任务。
3. 何时采用守护进程开发应用程序
以实际业务需求为例,需要运行一个程序监听特定端口,持续接收服务端发送的数据,经过分析处理后写入数据库,此处使用 ZeroMQ 实现数据的收发功能。
若不采用守护进程模式,程序运行时将占用当前终端窗口,并受键盘输入干扰,可能导致程序意外退出。
4. 守护进程的安全问题
出于安全考虑,应尽量避免以超级用户(root)身份运行程序。这样即使程序存在漏洞被黑客控制,攻击者也只能继承当前的普通用户权限,而无法获取系统的最高控制权。
此外,应限制程序仅能运行单个实例,避免同时开启多个副本,从而防止端口冲突等潜在问题。
5. 怎样开发守护进程
例 1. 守护进程示例
<?php
class ExampleWorker extends Worker {
#public function __construct(Logging $logger) {
# $this->logger = $logger;
#}
#protected $logger;
protected static $dbh;
public function __construct() {
}
public function run(){
$dbhost = '192.168.2.1'; // 数据库服务器
$dbport = 3306;
$dbuser = 'www'; // 数据库用户名
$dbpass = 'qwer123'; // 数据库密码
$dbname = 'example'; // 数据库名
self::$dbh = new PDO("mysql:host=$dbhost;port=$dbport;dbname=$dbname", $dbuser, $dbpass, array(
/* PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'', */
PDO::MYSQL_ATTR_COMPRESS => true,
PDO::ATTR_PERSISTENT => true
)
);
}
protected function getInstance(){
return self::$dbh;
}
}
/* the collectable class implements machinery for Pool::collect */
class Fee extends Stackable {
public function __construct($msg) {
$trades = explode(",", $msg);
$this->data = $trades;
print_r($trades);
}
public function run() {
#$this->worker->logger->log("%s executing in Thread #%lu", __CLASS__, $this->worker->getThreadId() );
try {
$dbh = $this->worker->getInstance();
$insert = "INSERT INTO fee(ticket, login, volume, `status`) VALUES(:ticket, :login, :volume,'N')";
$sth = $dbh->prepare($insert);
$sth->bindValue(':ticket', $this->data[0]);
$sth->bindValue(':login', $this->data[1]);
$sth->bindValue(':volume', $this->data[2]);
$sth->execute();
$sth = null;
/* ...... */
$update = "UPDATE fee SET `status` = 'Y' WHERE ticket = :ticket and `status` = 'N'";
$sth = $dbh->prepare($update);
$sth->bindValue(':ticket', $this->data[0]);
$sth->execute();
//echo $sth->queryString;
//$dbh = null;
}
catch(PDOException $e) {
$error = sprintf("%s,%s\n", $mobile, $id );
file_put_contents("mobile_error.log", $error, FILE_APPEND);
}
}
}
class Example {
/* config */
const LISTEN = "tcp://192.168.2.15:5555";
const MAXCONN = 100;
const pidfile = __CLASS__;
const uid = 80;
const gid = 80;
protected $pool = NULL;
protected $zmq = NULL;
public function __construct() {
$this->pidfile = '/var/run/'.self::pidfile.'.pid';
}
private function daemon(){
if (file_exists($this->pidfile)) {
echo "The file $this->pidfile exists.\n";
exit();
}
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
//pcntl_wait($status); //Protect against Zombie children
exit($pid);
} else {
// we are the child
file_put_contents($this->pidfile, getmypid());
posix_setuid(self::uid);
posix_setgid(self::gid);
return(getmypid());
}
}
private function start(){
$pid = $this->daemon();
$this->pool = new Pool(self::MAXCONN, \ExampleWorker::class, []);
$this->zmq = new ZMQSocket(new ZMQContext(), ZMQ::SOCKET_REP);
$this->zmq->bind(self::LISTEN);
/* Loop receiving and echoing back */
while ($message = $this->zmq->recv()) {
//print_r($message);
//if($trades){
$this->pool->submit(new Fee($message));
$this->zmq->send('TRUE');
//}else{
// $this->zmq->send('FALSE');
//}
}
$pool->shutdown();
}
private function stop(){
if (file_exists($this->pidfile)) {
$pid = file_get_contents($this->pidfile);
posix_kill($pid, 9);
unlink($this->pidfile);
}
}
private function help($proc){
printf("%s start | stop | help \n", $proc);
}
public function main($argv){
if(count($argv) < 2){
printf("please input help parameter\n");
exit();
}
if($argv[1] === 'stop'){
$this->stop();
}else if($argv[1] === 'start'){
$this->start();
}else{
$this->help($argv[0]);
}
}
}
$cgse = new Example();
$cgse->main($argv);
5.1. 程序启动
以下是程序启动后转入后台运行的核心代码逻辑。
通过检查进程ID文件的存在与否来判断当前进程状态。若 `file_exists($this->pidfile)` 返回真,表示程序已在运行中。需注意,若进程被强制杀死,需手动删除该文件才能重新启动。
private function daemon(){
if (file_exists($this->pidfile)) {
echo "The file $this->pidfile exists.\n";
exit();
}
$pid = pcntl_fork();
if ($pid == -1) {
die('could not fork');
} else if ($pid) {
// we are the parent
//pcntl_wait($status); //Protect against Zombie children
exit($pid);
} else {
// we are the child
file_put_contents($this->pidfile, getmypid());
posix_setuid(self::uid);
posix_setgid(self::gid);
return(getmypid());
}
}
程序启动后,父进程会退出,子进程则在后台继续运行。子进程的权限会从 root 切换到指定的普通用户,并将新的进程ID写入PID文件。
5.2. 程序停止
停止程序时,只需读取PID文件获取进程ID,然后调用 `posix_kill($pid, 9)` 发送终止信号,最后删除PID文件即可。
private function stop(){
if (file_exists($this->pidfile)) {
$pid = file_get_contents($this->pidfile);
posix_kill($pid, 9);
unlink($this->pidfile);
}
}