我需要杀死Windows中的一个进程,但我在同一个进程ID下有2个脚本

问题描述 投票:0回答:1

我有下一个问题:我正在运行一个 php 脚本的 url,该脚本对 mongoDb 进行查询并带来大量寄存器,这需要将近一个小时才能完成。到目前为止,一切都很顺利,问题是,如果用户关闭导航器窗口,这个脚本会继续运行,这是可以的,但是如果他再次打开所有内容并运行该脚本,我需要在 Windows 中搜索上一个进程并杀死它。 试图做到这一点,当我运行脚本时,我首先使用 getmypid() 函数询问进程 ID,然后将其插入到 Mongo 的集合中,如果一切都结束了,我将其保存在该集合中,但如果这个,由于某种原因,还没有发生并且结局没有保存,然后我搜索那个pid并杀死它。最大的问题是第一个进程在例如de pid = 926下运行,而我现在运行的脚本在相同的pid下。当我杀死第一个实际运行的进程时,它也会杀死我的实际进程。

这是代码的一部分:

$queryProcess = [ 'id_register' => $_SESSION['applicationId'], 'name_process' => 'validation_process' ];

    $cursorProcess = queryMongo(DBNAME, 'process', $queryProcess, ['$sort' => ['date_process' => 1]]); 
    
    $date_last = null;
    $status_last = null;
    
    foreach ($cursorProcess as $process) {
                         
        $reInitExistence = strpos($process['status_process'], 're-init');

        if($reInitExistence === 0){
            $process['status_process'] = substr($process['status_process'], 0, 7);
        }

        if ($date_last === null || $date_last <= $process['date_process']) {
            $date_last = $process['date_process'];
            $status_last = $process['status_process'];
            $pId = $process['pId'];
         }
    } 
    if ($status_last === 'init' || $status_last === 're-init') {

       killIfRunning($pId);
                              
    }

这是killIfRunning函数:

function killIfRunning($pid) {
    $pipes = [];
    $status = proc_get_status(proc_open("tasklist /FI \"PID eq $pid\" /NH", [["pipe", "r"], ["pipe", "w"], ["pipe", "w"]], $pipes));
    if ($status !== false && $status['running'] === true) {

        exec("taskkill /F /PID $pid", $output, $returnCode);
        if ($returnCode == 0) {
            echo "Proceso con PID $pid finalizado correctamente.";
        } else {
            throw new Exception('El proceso iniciado no logró finalizarse con exito.');
        }
    }
}

提前致谢。

php mongodb windows process pid
1个回答
0
投票

您收到的 PID 是 Apache 服务器的 PID。因此,当您尝试杀死它时,您会杀死 Apache 及其子进程(Apache 执行的 PHP 脚本)。

您可以设置不同的方法。例如,您想要结束的脚本可以检查某些信号(例如文件、数据库记录),如果找到它,它将使用

exit()
自行终止。

这是您需要从浏览器运行的东西吗?如果是定期执行的任务,那么使用 PHP 二进制文件的 Cron 会更好。

© www.soinside.com 2019 - 2024. All rights reserved.