I spawn a child process. After I spawn it, I write to the outgoing stream, so I want to synchronously detect if it failed to spawn before doing that (otherwise I get a write EPIPE
error).
let proc = cp.spawn("path/file.exe");
proc.on("error", (err) => { throw err; });
proc.stdin.write(...);
Now if I put the write
on a setTimeout(() => { proc.stdin.write(...); }, 0)
, the error
handler will get hit first, and we'll crash before doing the write
, but that's a little ugly.
What I have found is that after cp.spawn
returns, we can check the proc.pid
property, and if it's a number, we know that the process spawned. If we give it the path of a nonexistent executable, proc.pid
is undefined
, so it seems that we can synchronously check if the process failed to spawn, and we don't need to rely on the asynchronous error
callback (though the callback catches other errors).
Node's documentation has a section on checking for a failed spawn, but it suggests the asynchronous method:
const subprocess = spawn('bad_command');
subprocess.on('error', (err) => {
console.log('Failed to start subprocess.');
});
Nowhere does it mention that checking for an undefined
proc.pid
is a suitable synchronous alternative for checking for a failed spawn, which me leads to wonder if this a robust and recommended way of doing it. Can anyone comment on this?
error
handler? In that case, I take it that I'm forced to not do thewrite
synchronously. However, I don't see anysuccess
type of event. So must I do thesetTimeout(()=>{}, 0)
thing, or is there a better way? I guess I could try to ping the process by sending it a message...error
event. It seems like ifproc.stdin
exists, you should be able to write to it without error. It is a stream so you may have to pay attention to flow control if you're writing larger amounts.sapwnSync()
?