TL;DR : How does one fork a process that is located outside of the current running process?
I'm trying to use child_process
of Nodejs in order to start another nodejs process on the parent's process exit.
I successfully executed the process with the exec
but I need the child process be independent of the parent, so the parent can exit without waiting for the child, hence I tried using spawn
with the detached: true, stdio: 'ignore'
option and unref()
ing the process:
setting options.detached to true makes it possible for the child process to continue running after the parent exits.
spawn('node MY_PATH', [], {detached: true, stdio: 'ignore'}).unref();
This yields the :
node MY_PATH ENOENT
error. which unfortunately I've failed resolve.
After having troubles achieving this with spawn
and reading the documentationagain i figured i should actually use fork
:
The child_process.fork() method is a special case of child_process.spawn() used specifically to spawn new Node.js processes.
fork()
doesnt take a command as its' first argument, but a modulePath
which i can't seem to fit since the script I'm trying to run as a child process isnt in the directory of the current running process, but in a dependency of his.
Back to the starting TL;DR - how does one fork a process that is located outside of the current running process?
Any help would be much appreciated!
EDIT:
Providing a solution to the spawn
ENOENT error could be very helpfull too!
The purpose of fork() is to create a new process, which becomes the child process of the caller. After a new child process is created, both processes will execute the next instruction following the fork() system call.
fork() method in Python is used to create a child process. This method work by calling the underlying OS function fork(). This method returns 0 in the child process and child's process id in the parent process. Note: os. fork() method is available only on UNIX platforms.
So there are total eight processes (new child processes and one original process).
This fork system call is used to create a new process. This newly created process is known as child process. The current process which is creating another child process is called the parent process. A child process uses the same program counter, CPU register, same files that are used by the parent process.
Following code should allow you to do what you need.
var Path = require('path');
var Spawn = require('child_process').spawn;
var relative_filename = '../../node_modules/bla/bla/bla.js';
Spawn('node', [Path.resolve(__dirname, relative_filename)], {detached: true, stdio: 'ignore'}).unref();
process.exit(0);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With