从php运行node file.js并在卸载时将其杀死-Windows [英] Run node file.js from php and kill it on unload - Windows
问题描述
我的目标是在脚本开始时从我的php页面运行一个节点文件,然后在关闭页面时终止该进程.我一直在读一些没有运气的问题和答案.我可以通过示例来运行
my goal is to run a node file from my php page at the start of my script and then kill that process when the page is closed. I have been reading several questions and answers without luck. I can run by example
exec("node myapp.js arg1 arg2 2>&1", $retArr);
在我的节点文件中添加:
In my node file i added:
console.log(process.pid);
因此,现在我在输出数组上接收到该进程的PID,但是必须结束该操作,以后我可以使用exec('taskkill/PID'.$ array [x].'/f')将其杀死.我如何才能从php获取该进程pid,以仅杀死该进程??
So now i receive the PID of the process on the output array but have to be ended, with this i could kill it later with exec('taskkill /PID '.$array[x].' /f'), how i can get that process pid from php to kill only that one?.
任何灯都将不胜感激.预先感谢.
Any lights will be REALLY appreciated. Thanks in advance.
推荐答案
Windows用户:
Windows Users:
好吧,如果有人遇到相同的问题,我找到了解决此问题的方法.
Ok I found a workaround for this situation in case someone face the same issue.
节点应用程序需要侦听已定义的端口,因此您可以将该端口作为参数传递给节点应用程序,而我需要从所有可能的解决方案中在PHP的开头在后台启动该节点应用程序.一个是最适合我的一个:
The node app need to listen in a defined port, so you can pass that port to the node app as argument and I needed to start that node app in the background at the beginning of my PHP, from all the possible solutions this one was the one that worked best for me:
$rshell = new COM("WScript.Shell");
$rexec = $rshell->Run("node C:\PATH\TO\NODE\APP\myapp.js ".$appPort." ", 0, false);
这将在后台运行该应用,并且您的侦听端口位于一个变量中.
this will run the app in the background and you have the listening port in a variable.
Node应用程序可以接收参数,您可以使用以下参数检索它们:
Node apps can receive arguments and you can retrieve them using:
process.argv.forEach((val, index) => {
console.log(`${index}: ${val}`);
});
var appPort = process.argv[2];
...
app.listen(appPort);
回到PHP
好的,到目前为止,您可以在后台从php启动节点应用程序,并且具有侦听端口,因此现在我们创建一个新的php文件来处理关闭过程,假设closeNode.php可以接收我们的侦听通过AJAX onunload变量:
Back to the PHP
Fine, so far you can start up the node app from php in the background and you have the listening port, so now we create a new php file to handle the closing process, lets say closeNode.php that will receive our listening variable via AJAX onunload :
$( window ).unload(function() {
<!-- your ajax call sending the appPort variable-->
});
closingNode.php
$appPort = $_POST('appPort')
exec('netstat -a -n -o | find "LISTENING" | find "'.$appPort.'"', $result);
if (!empty($result)) {
$pidArray = array();
foreach ($result as $value) {
// our pid is at the end of the string, then we trim the last 10 characters that is enough for the pid process number
$pidArray[] = substr($value, -10);
}
$pidTrimmed = array_map('trim', $pidArray);
$pid = $pidTrimmed[0];
exec('taskkill /f /PID '.$pid.'', $resultKill);
也许不是更优雅的解决方案,但它可以工作.
Maybe is not the more elegant solution, but it works.
这篇关于从php运行node file.js并在卸载时将其杀死-Windows的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!