I am using the following code to spawn a child process that asks the user for input and then it should complete, but the close
event is never fired.
const spawn = require('child_process').spawn;
const p = spawn('script', ['that', 'prompts', 'user', 'for', 'input']);
process.stdin.on('data', (data) => {
p.stdin.write(data);
});
p.on('close', (code) => {
console.log(`child process closed with code ${code}`);
});
If I spawn a process that doesn't prompt for user input (like lsĀ“), the
close` event fires without any issue. I suspect something about writing directly into the child process's STDIN from the parent is preventing it from terminating correctly but I can't figure out why. Am I missing something obvious here?
I have written directly into child-processes over stdin and handled it but attaching a listener for 'finish' event on stdout of the child process. Perhaps it will apply to your use-case scenario, perhaps not.
If it helps you can read over the code I had used to implement it. code here. Please note the code is a bit messy still, it was a rudimentary approach toward producing a module to allow child processes to run Linux commands using sudo privileges within a non-root parent process; in order to do this I needed a way to supply the password for sudo. The idea was to allow the password to be passed in from a configuration file, from stdin prompt, or resolved from a Promise asynchronously such as fetched from a database where it could be stored encrypted and potentially unencrypted along the way. Eventually I would like to revisit that code and re-write it much better, so what you see is just a proof of concept/experimenting. Also it is written in ES6+ (Arrow Functions, Promises, Classes, Constructors).