簡體   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