Reputation: 113345
I'm using spawn
for creating child processes. I want to create a child process and after it is started I want to exit the current process.
var Spawn = require("child_process").spawn;
var sp = Spawn("sleep", ["10000"]);
sp.unref();
process.exit();
The code above works fine: it creates a child process (sleep
) which will live 10 seconds and the current process is exited.
Can I be sure that when I do process.exit()
the sleep
process is active or by ending the parent process the child process will be killed as well?
In this is a simple example, process.exit()
is useless since the process will end anyway because I call unref
. However, this is just an example.
So, is there any event to listen to comming from sp
(the child process) which tells me that hey I'm active?
In some cases (e.g. var sp = Spawn("node", ["foo", "--bar"]);
) I see [nodejs] <defunct>
in the output of ps aux | grep node
, right after the spawn call. This happens in the debugging mode where I can control the app running. That means the process is not yet active, I guess.
Upvotes: 0
Views: 801
Reputation: 70065
Looking at the io.js
source, child_process.spawn()
calls ChildProcess.spawn()
which sets the .pid
property only after all the error checking has happened. So one thing you can do is check to see if the pid
property is set on the object returned by spawn()
and if it is, then you can be assured that your child process successfully launched.
(It might be better to look closely at how all the errors are propagated back and handle them instead of relying on the pid
. Or maybe pid
is totally reliable because you can't have a pid
without a process? Someone who knows more want to weigh in with a comment or edit this answer directly to improve it?)
If you want the child process to continue running after your code exits, you will want to set options.detached
. Otherwise, the child process will exit when the parent process exits.
defunct
is explained in the ps
man page:
Processes marked are dead processes (so-called "zombies") that remain because their parent has not destroyed them properly. These processes will be destroyed by init(8) if the parent process exits."
Upvotes: 2