如何杀死npm子进程
我有一个package.json
,我定义了一个debug
脚本。这个脚本启动了一个node
应用程序。
整个npm
脚本是通过测试启动的,一旦测试结束,最后一个必须杀死debug
脚本。
所以,当我spawn
npm run debug
和我杀了它时,node
进程没有被杀死。
我试图用child_process.kill
杀死整个过程并产生一个没有运气的kill
bash命令,因为pid
不属于使用node
发射的npm run debug
。
如何杀死我没有node
的pid
进程?
您没有必要拥有PID才能杀死它(只要运行脚本的用户有权这样做)。
您可以生成命令并像在命令行中那样执行它(其中有多种方式)。还有像find-process
这样的软件包,您也可以使用它来查找过程。
更简单的方法是在debug
启动时编写一些包含pid的文件(如果可以的话)。然后你可以重新读取该文件以获得PID。
// in debug
import { writeFile } from 'fs';
writeFile('debug.pid', process.pid, 'utf8', err => err && console.log('Error writing pid file'));
// in app where it'll kill
import { readFile } from 'fs';
let debugPid;
readFile('debug.pid', 'utf8', (err, data) => err ? console.log('Error reading pid file') : debugPid = data);
无论方法如何,一旦你有了PID,使用process.kill()
来杀死它:
process.kill(pid);