我试图在javascript中生成一个进程,并在一段时间后将其杀死(出于测试目的).
最后,这个过程将是一个无限循环,我需要在指定的时间用不同的参数重新启动,所以我认为生成并终止这个过程是最好的方法.
我的测试代码是:
var spawn=require('child_process').spawn
, child=null;
child=spawn('omxplayer', ['test.mp4'], function(){console.log('end');}, {timeout:6000});
console.log('Timeout');
setTimeout(function(){
console.log('kill');
child.kill();
}, 1200);
child.stdout.on('data', function(data){
console.log('stdout:'+data);
});
child.stderr.on('data', function(data){
console.log('stderr:'+data);
});
child.stdin.on('data', function(data){
console.log('stdin:'+data);
});
结果是:
#~$ node test.js
Timeout
kill
但我仍然需要发送ctrl+C来结束程序.我错过了什么?
在 node 0.10.17的Raspbian上,omxplayer是一个二进制(视频播放器).
我试过:
- 在应用程序中添加了
chmod +x
个. - 以root用户身份启动.
- 已暂停子进程的stdin.使用kill命令中的所有终止相关信号.
在运行应用程序ps
时,我也启动了一个命令:
2145 bash
2174 node
2175 omxplayer
2176 omxplayer.bin
2177 ps
所以omxplayer是一个包装器,当它结束时,它不会杀死它的子进程,有没有办法获得包装进程的pid?
仍然咬着灰尘,试着这样做:
spawn('kill', ['-QUIT', '-$(ps opgid= '+child.pid+')']);
我认为这会杀死omxplayer的所有子元素,我不知道这样使用spawn是错误的还是代码不起作用.
我最后一次编辑的答案是正确的,但必须进行一些编辑.
我创建了一个sh文件(具有执行权限),如下所示:
PID=$1
PGID=$(ps opgid= "$PID")
kill -QUIT -"$PGID"
我是这样开始的:
execF('kill.sh', [child.pid], function(){
console.log('killed');
});
而不是child.kill
.
我不确定这是否是最好的方法,也不确定代码是否干净,但它确实有效.
我会接受任何更简洁的答案,甚至更好,不需要执行文件.