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



我的脚本旨在从这个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。

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

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变量就会为您提供带有child.pid的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                           
})

最新更新