Spawn and kill a process in node.js

Why don't you just send the 'q' value in the stdin pipe ? It kill the omxplayer process.


Refer to this discussion

Once you start listening for data on stdin, node will wait for the input on stdin until it is told not to. When either user presses ctrl-d (meaning end of input) or the program calls stdin.pause(), node stops waiting on stdin.

A node program does not exit unless it has nothing to do or wait for. Whats happening is, it is waiting on stdin and therefore never exits.

Try changing your setTimeout callback to

console.log('kill');
child.stdin.pause();
child.kill();

I hope that should work.


I've had exactly the same issue as you with omxplayer and the solution in this blog post worked for me.

var psTree = require('ps-tree');

var kill = function (pid, signal, callback) {
    signal   = signal || 'SIGKILL';
    callback = callback || function () {};
    var killTree = true;
    if(killTree) {
        psTree(pid, function (err, children) {
            [pid].concat(
                children.map(function (p) {
                    return p.PID;
                })
            ).forEach(function (tpid) {
                try { process.kill(tpid, signal) }
                catch (ex) { }
            });
            callback();
        });
    } else {
        try { process.kill(pid, signal) }
        catch (ex) { }
        callback();
    }
};

// elsewhere in code
kill(child.pid);

There is a really neat npm package called tree-kill which does this very easily and effectively. It kills the child process, and all child processes that child may have started.

var kill  = require('tree-kill');
const spawn = require('child_process').spawn;

var scriptArgs = ['myScript.sh', 'arg1', 'arg2', 'youGetThePoint'];
var child = spawn('sh', scriptArgs);

// some code to identify when you want to kill the process. Could be
// a button on the client-side??
button.on('someEvent', function(){
    // where the killing happens
    kill(child.pid);
});