我有一个脚本,它回显一些内容并关闭与客户端的连接,但是它将在后台工作以处理一些电子邮件。
有没有办法跟踪后台进程的状态?我的意思是它已完成,或仍在运行等。
目前我在进程开始和进程结束时在数据库上设置一个标志。但我担心有时脚本在某些情况下可能会失败。
前任。从服务器主机强制终止。
当脚本停止执行时,是否有任何可能的方法来触发函数(通过退出,强制停止任何......)
我在 windows/linux 服务器上运行脚本,两者都是共享主机,没有 CRON、任务计划程序支持。
谢谢你。
在 linux 服务器中,您可以通过以下代码检查脚本状态
$output = array();
exec("ps aux | grep -i YOUR_SCRIPT | grep -v grep", $output);
if (empty($output)) {
// your script is not running
doSomething();
}
我没有测试 windows 部分,所以它可能有点错误。但我认为这个概念是相似的。
$name = 'YOUR_SCRIPT';
if (!isRunning($name)) {
// script is not running
doSomething();
}
function isRunning($scriptname)
{
$output = array();
if (strtoupper(substr(php_uname(), 0, 3)) === 'WIN') {
// Windows os
exec("tasklist | find \"{$scriptname}\"", $output);
} else {
// Not window os, maybe linux, freebsd..etc
exec("ps aux | grep -i $scriptname | grep -v grep", $output);
}
return !empty($output);
}
不完全确定我在这里是否正确,但我假设您希望记录后台进程的活动而不实际连接到它。
如果是这样,也许最简单的方法是让进程创建一个 txt 日志文件,您可以在需要检查以查看发生了什么时访问该文件。只需使用 fwrite() 根据需要附加文件。
您也可以将 mysql 数据库表用于相同目的,其优点是更易于阅读。
如果您需要在没有发生任何事情(或某些特定事情)时主动警告您,您可以使用您的头文件或连接函数在每次用户加载页面时为您检查。如果您有足够的点击量,您将收到一封电子邮件 pdq。
你确定你没有cron吗?请检查 cpanel - 它可能隐藏在那里。
上面的答案是对的。之后,如果您想停止该进程,您可以终止该进程,您可以通过
kill -9 PID
您将在输出数组中获得 PID。在 if 语句中使用它。
$output = array();
exec("ps aux | grep -i YOUR_SCRIPT | grep -v grep", $output);
if (empty($output)) {
$kill = " kill -9 ".$output['PID'] // Print the output array to get exact index for PID
exec($kill);
}