如何停止在后台运行的PHP脚本

Ric*_*hie 14 php apache

我开始了这个过程(time.php)

<?php

ignore_user_abort(true); // run script in background
set_time_limit(0);       // run script forever 
$interval = 300;         // do every 1 minute...
do
{ 
    // add the script that has to be ran every 1 minute here
    // ...

    $to      = "xxxxxxxxx@gmail.com";
    $subject = "Hello Richie";
    $header  = "From: me@xxxxxxxxx.org";
    $body    = "Hello Richard,\n\n"
             . "I was just testing this service\n\n "
             . "Thanks! ";

    mail($to, $subject, $body, $header);

    sleep($interval); // wait 5 minutes

} while(true); 
?>
Run Code Online (Sandbox Code Playgroud)

但我现在想阻止它.它将数百封邮件发送到我的Gmail A/c.它位于Web服务器上,我无法重新启动它以终止进程.

有没有办法执行另一个文件来杀死进程,或者我该怎么办?

Eri*_*c P 19

如果您没有shell访问权限,那么唯一的方法是让服务器管理员终止该进程.

话虽如此,有一种简单的方法可以设置脚本并使其从同一服务器上的任何其他脚本中取消,如下所示:

<?php
// at start of script, create a cancelation file

file_put_contents(sys_get_temp_dir().'/myscriptcancelfile','run');

// inside the script loop, for each iteration, check the file

if ( file_get_contents(sys_get_temp_dir().'/myscriptcancelfile') != 'run' ) { 
    exit('Script was canceled') ; 
}

// optional cleanup/remove file after the completion of the loop

unlink(sys_get_temp_dir().'/myscriptcancelfile');

// To cancel/exit the loop from any other script on the same server

file_put_contents(sys_get_temp_dir().'/myscriptcancelfile','stop');

?>
Run Code Online (Sandbox Code Playgroud)


Jor*_*ack 8

我假设你也没有shell访问权限.我怀疑最简单的方法是联系管理员并让他们重新启动Apache.他们不希望这种运行比你更多.

一种替代方法是尝试使用PHP杀死所有Apache进程.它将向所有Apache进程发送一个kill信号,除了它运行的那个进程.如果Apache进程在没有setuid()的共享进程下运行,这可能会有效.尝试自担风险.

<?php
$cpid = posix_getpid();
exec("ps aux | grep -v grep | grep apache", $psOutput);
if (count($psOutput) > 0)
{
    foreach ($psOutput as $ps)
    {
        $ps = preg_split('/ +/', $ps);
        $pid = $ps[1];

        if($pid != $cpid)
        {
          $result = posix_kill($pid, 9); 
        }
    }
}
?>
Run Code Online (Sandbox Code Playgroud)


Roy*_*M J 5

以下将停止后台进程(PHP):

sudo service apache2 stop
Run Code Online (Sandbox Code Playgroud)

再次启动apache:

sudo service apache2 start
Run Code Online (Sandbox Code Playgroud)

简单地重新启动apache:

sudo service apache2 start
Run Code Online (Sandbox Code Playgroud)


Aar*_*way 0

您可以终止正在运行的 apache 进程。尝试运行类似的命令apachectl stop,然后apachectl start将其重新启动。这将在一段时间内杀死您的服务器,但它也将确保卡在该脚本上的任何进程都会消失。