123456789101112131415161718192021222324252627282930313233343536373839404142434445 |
- import {exec, spawn} from 'child_process';
- class ProcessManager {
- constructor() {
- this.processes = new Map(); // 存储所有子进程的引用
- }
- // 启动新的子进程
- startProcess(key, command, callback) {
- // 如果相同 key 的进程已经在运行,先终止它
- if (this.processes.has(key)) {
- this.killProcess(key);
- }
- // 启动新进程
- const child = exec(command, (error, stdout, stderr) => {
- if (callback) callback(error, stdout, stderr); // 执行回调
- // 执行完成后,清理存储的进程
- this.processes.delete(key);
- });
- // 存储进程引用
- this.processes.set(key, child);
- }
- // 终止指定 key 的子进程
- killProcess(key) {
- const child = this.processes.get(key);
- if (child) {
- child.kill();
- this.processes.delete(key);
- }
- }
- // 终止所有子进程
- killAll() {
- for (const [key, child] of this.processes.entries()) {
- child.kill();
- this.processes.delete(key);
- }
- }
- }
- export default ProcessManager;
|