我的脚本旨在从此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';
}
});
关于javascript - 返回Node.js子进程的pid的最简单方法,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/53494363/