php实现监听
监听文件变化
使用PHP内置的inotify扩展可以监听文件系统事件。需要确保服务器安装了inotify扩展并启用。
$watcher = inotify_init();
$watchDescriptor = inotify_add_watch($watcher, '/path/to/directory', IN_MODIFY);
while (true) {
$events = inotify_read($watcher);
foreach ($events as $event) {
echo "File {$event['name']} was modified\n";
}
}
监听网络端口
通过socket扩展可以创建TCP/UDP服务器监听端口。
$socket = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);
socket_bind($socket, '0.0.0.0', 8080);
socket_listen($socket);
while (true) {
$client = socket_accept($socket);
$data = socket_read($client, 1024);
echo "Received: $data";
socket_close($client);
}
监听数据库变化
使用数据库触发器结合PHP轮询可以实现监听表变化。
$pdo = new PDO('mysql:host=localhost;dbname=test', 'user', 'pass');
$lastId = 0;
while (true) {
$stmt = $pdo->query("SELECT * FROM table WHERE id > $lastId ORDER BY id DESC LIMIT 1");
if ($row = $stmt->fetch()) {
$lastId = $row['id'];
echo "New record: " . json_encode($row);
}
sleep(1);
}
监听进程状态
通过proc_open和stream_select可以监听子进程输出。
$descriptors = [
0 => ["pipe", "r"],
1 => ["pipe", "w"],
2 => ["pipe", "w"]
];
$process = proc_open('long-running-command', $descriptors, $pipes);
while (true) {
$read = [$pipes[1]];
$write = $except = null;
if (stream_select($read, $write, $except, 0, 200000) > 0) {
echo fread($pipes[1], 8192);
}
if (!proc_get_status($process)['running']) {
break;
}
}
监听Redis订阅
使用phpredis扩展可以监听Redis的发布/订阅频道。

$redis = new Redis();
$redis->connect('127.0.0.1', 6379);
$redis->subscribe(['channel_name'], function ($redis, $channel, $message) {
echo "Received $message from $channel\n";
});






