subprocess.ref()


在调用 subprocess.unref() 后调用 subprocess.ref() 将为子进程恢复删除的引用计数,迫使父进程在退出之前等待子进程退出。

const { spawn } = require('node:child_process');

const subprocess = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: 'ignore'
});

subprocess.unref();
subprocess.ref();

Calling subprocess.ref() after making a call to subprocess.unref() will restore the removed reference count for the child process, forcing the parent to wait for the child to exit before exiting itself.

const { spawn } = require('node:child_process');

const subprocess = spawn(process.argv[0], ['child_program.js'], {
  detached: true,
  stdio: 'ignore'
});

subprocess.unref();
subprocess.ref();