Tạo một daemon.
Nếu bạn đang sử dụng symfony2, bạn có thể sử dụng Process Component.
// in your server start command
$process = new Process('/usr/bin/php bin/chat-server.php');
$process->start();
sleep(1);
if ($process->isRunning()) {
echo "Server started.\n";
} else {
echo $process->getErrorOutput();
}
// in your server stop command
$process = new Process('ps ax | grep bin/chat-server.php');
$process->run();
$output = $process->getOutput();
$lines = preg_split('/\n/', $output);
// kill everything (there can be multiple processes if they are spawned)
$stopped = False;
foreach ($lines as $line) {
$ar = preg_split('/\s+/', trim($line));
if (in_array('/usr/bin/php', $ar)
and in_array('bin/chat-server.php', $ar)) {
$pid = (int) $ar[0];
posix_kill($pid, SIGKILL);
$stopped = True;
}
}
if ($stopped) {
echo "Server stopped.\n";
} else {
echo "Server not found. Are you sure it's running?\n";
}
Nếu bạn đang sử dụng PHP gốc, không bao giờ sợ hãi, popen
là bạn của bạn!
// in your server start command
_ = popen('/usr/bin/php bin/chat-server.php', 'r');
echo "Server started.\n";
// in your server stop command
$output = array();
exec('ps ax | grep bin/chat-server.php', &$output);
$lines = preg_split('/\n/', $output);
// kill everything (there can be multiple processes if they are spawned)
$stopped = False;
foreach ($lines as $line) {
$ar = preg_split('/\s+/', trim($line));
if (in_array('/usr/bin/php', $ar)
and in_array('bin/chat-server.php', $ar)) {
$pid = (int) $ar[0];
posix_kill($pid, SIGKILL);
$stopped = True;
}
}
if ($stopped) {
echo "Server stopped.\n";
} else {
echo "Server not found. Are you sure it's running?\n";
}
Có tất nhiên các thư viện PHP hữu ích khác để làm việc với daemon. Googling "php daemon" sẽ cung cấp cho bạn rất nhiều con trỏ.
Hướng dẫn này cho thấy một cách thực sự mát mẻ của biến WebSocket vào một dịch vụ * nix để làm cho nó tồn tại ngay cả khi bạn đóng kết nối SSH của mình. http://blog.samuelattard.com/the-tutorial-for-php-websockets-that-i-wish-had-existed/ – MarshallOfSound