crutch / daemon
守护进程辅助工具
v1.1.0
2023-07-04 23:17 UTC
Requires
- php: ^7.4 || ^8.0
- ext-pcntl: *
- ext-posix: *
This package is not auto-updated.
Last update: 2024-09-12 00:19:19 UTC
README
守护进程辅助工具
安装
composer require crutch/daemon:^1.0
使用
创建工作运行器
#!/usr/bin/env php <?php // crutch_worker_demo.php declare(strict_types=1); require_once __DIR__ . '/vendor/autoload.php'; $worker = function () { while (true) { sleep(1); } }; $pidFile = '/tmp/crutch-daemon.pid'; $daemon = new \Crutch\Daemon\Daemon($pidFile); $action = $argv[1] ?? ''; $num = max(1, intval($argv[2] ?? '1')); switch ($action) { case 'start': try { $daemon->start($worker, $num); } catch (\Crutch\Daemon\Exception\DaemonException $exception) { printf("Could not start daemon: %s\n", $exception->getMessage()); exit($exception->getCode()); } break; case 'listen': $daemon->listen($worker); break; case 'stop': try { $daemon->stop(); } catch (\Crutch\Daemon\Exception\DaemonException $exception) { printf("Could not stop daemon: %s\n", $exception->getMessage()); exit($exception->getCode()); } break; default: print("unknown action\n"); exit(127); }
运行它
php ./crutch_worker_demo.php start 3
检查进程
ps aux | grep crutch_worker_demo
user 58576 0.0 0.0 140080 11624 ? Ss 17:58 0:00 php ./crutch_worker_demo.php start
user 58577 0.0 0.0 140080 9584 ? S 17:58 0:00 php ./crutch_worker_demo.php start
user 58578 0.0 0.0 140080 9584 ? S 17:58 0:00 php ./crutch_worker_demo.php start
user 58579 0.0 0.0 140080 9584 ? S 17:58 0:00 php ./crutch_worker_demo.php start
user 58580 0.0 0.0 9116 2488 pts/3 S+ 17:58 0:00 grep --color=auto crutch_worker_demo
您看到1个父进程(PID=58576)和3个子进程(PIDs=58577, 58578和58579)。进程58580是grep,忽略它。
停止进程
php ./crutch_worker_demo.php stop
检查进程
ps aux | grep crutch_worker_demo
user 59825 0.0 0.0 9116 2488 pts/3 S+ 17:58 0:00 grep --color=auto crutch_worker_demo
所有进程已被杀死。