1.创建 test.php 文件
<?php
while (true) {
try {
$content=mt_rand(1,200)."\n";
$file='./test.txt';
if($f = file_put_contents($file, var_export($content, true) . PHP_EOL, FILE_APPEND)){
}
// echo file_get_contents($file);
} catch (\Exception $e) {
echo 'error';
}
sleep(1);
}
?>
2.linux 下执行,如下:
nohup php test.php &
3. 查看日志文件 命令:tail -f test.txt
4. 关闭php后台进程 首先查看进程PID。 命令:ps -ef | grep "php test.php"
5. 然后,通过这个PID把该进程kill掉。命令:kill -9 23279
6.设置开机自启
在/etc/rc.local文件中,将nohup php test.php &
这个命令加入即可。注意:根据实际文件路径添加(如:nohup php /usr/local/src/test.php &)