Reputation: 89
Is there any way to spawn a new independent process from the current running script?
I am trying to run a new script from an already running script. The new script should be independent of the one that called it.
Upvotes: 5
Views: 3840
Reputation: 41
The accepted answer to this question is to use detached: true
and call unref()
on the spawned process. This is also what the documentation states.
However, using Node 10, I can't get the sub process (a shell script that restarts my Node process after other commands) to survive the Node process: it is always killed when the parent Node process is stopped, no matter how I do it (I also tried calling disconnect()
, but it does not work since there is no active IPC channel). I believe this is a bug in this version of Node (there's this official issue but for Windows).
My workaround is to use the at
command. Perhaps there's an equivalent for Windows, but this will work only for Linux.
So, instead of calling directly your shell script, you call the script by piping it to at
with a given execution date (if you just put "now" it will be executed right away)
echo /usr/sbin/my-script.sh arg1 | sudo at now
Upvotes: 0
Reputation: 360
You can use the 'detached' option and the unref() method to make child process independent.
const spawn = require('child_process').spawn;
const child = spawn(process.argv[0], ['child_program.js'], {
detached: true,
stdio: ['ignore']
});
child.unref();
Ref: Node.js document
Upvotes: 10