processManager.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import {exec, spawn} from 'child_process';
  2. class ProcessManager {
  3. constructor() {
  4. this.processes = new Map(); // 存储所有子进程的引用
  5. }
  6. // 启动新的子进程
  7. startProcess(key, command, callback) {
  8. // 如果相同 key 的进程已经在运行,先终止它
  9. if (this.processes.has(key)) {
  10. this.killProcess(key);
  11. }
  12. // 启动新进程
  13. const child = exec(command, (error, stdout, stderr) => {
  14. if (callback) callback(error, stdout, stderr); // 执行回调
  15. // 执行完成后,清理存储的进程
  16. this.processes.delete(key);
  17. });
  18. // 存储进程引用
  19. this.processes.set(key, child);
  20. }
  21. // 终止指定 key 的子进程
  22. killProcess(key) {
  23. const child = this.processes.get(key);
  24. if (child) {
  25. child.kill();
  26. this.processes.delete(key);
  27. }
  28. }
  29. // 终止所有子进程
  30. killAll() {
  31. for (const [key, child] of this.processes.entries()) {
  32. child.kill();
  33. this.processes.delete(key);
  34. }
  35. }
  36. }
  37. export default ProcessManager;