繁体   English   中英

返回nodejs子进程pid的最简单方法

[英]Simplest way to return pid of nodejs child process

我的脚本旨在从此 nodejs 脚本启动一个 python 程序。 (Nodejs 不是我的语言)。 我想在 python 脚本启动后确定它的 pid,然后随时终止它。 这是我的代码。

var pid = {};

v1.on('write', function(param) {
    if (param[0] == '1') {
            child = exec('python /home/pi/startup/motion.py',
            function (error, stdout, stderr) {
                console.log('stdout: ' + stdout);
                console.log('stderr: ' + stderr);
                if (error !== null) {
                     console.log('exec error: ' + error);
                }
            });
        writeVal = 'motion sensor ON'; 
    }
    else if (param[0] == '0') {
        child = exec('kill'+ pid,
            function (error, stdout, stderr) {
                console.log('stdout: ' + stdout);
                console.log('stderr: ' + stderr);
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
            });
        writeVal = 'Motion OFF';
    }
});

exec返回一个ChildProcess对象,因此您可以使用child.pid获取 pid。

您也可以直接使用child.kill()而不使用 shell 命令。

var child;

v1.on('write', function(param) {
    if (param[0] == '1') {
            child = exec('python /home/pi/startup/motion.py',
            function (error, stdout, stderr) {
                console.log('stdout: ' + stdout);
                console.log('stderr: ' + stderr);
                if (error !== null) {
                     console.log('exec error: ' + error);
                }
            });
        writeVal = 'motion sensor ON'; 
    }
    else if (param[0] == '0') {
        exec('kill '+ child.pid,
            function (error, stdout, stderr) {
                console.log('stdout: ' + stdout);
                console.log('stderr: ' + stderr);
                if (error !== null) {
                    console.log('exec error: ' + error);
                }
            });

        // 
        // child.kill()
        //

        writeVal = 'Motion OFF';
    }
});

我看到您已经创建了一个用于运行 python 的脚本。 我假设你有PID。 如果你不这样做,一旦你运行 python 脚本, child变量应该给你 PID 和child.pid

将其保存在pid变量中。 您可以使用以下命令终止任务。

-f是确保“强制杀死”

注意:/PID 后的空格是强制性的,以免出现参数错误

childProcess.exec('taskkill -f /PID ' + pid, function(err, stdout, stderr){
     var status = stdout.split(':')[0]
     if(status === 'SUCCESS'){ 
         //successfully killed
     } else if(status === 'ERROR'){
         //Ouch! PID does not exist
     }
     //Note: You get stdout for both the scenarios where PID is found and PID is not found                           
})

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM