92

I'm trying to spawn a process in javascript, and kill it after some time (for testing purposes).

In the end, the process will be a infinite loop that I need to restart with different arguments at specified time, so I thought that spawning the process and killing it was the best way to do this.

My test code is:

var spawn=require('child_process').spawn
, child=null;

child=spawn('omxplayer', ['test.mp4'], function(){console.log('end');}, {timeout:6000});
console.log('Timeout');
setTimeout(function(){
    console.log('kill');
    child.kill();
}, 1200);

child.stdout.on('data', function(data){
    console.log('stdout:'+data);
});

child.stderr.on('data', function(data){
    console.log('stderr:'+data);
});

child.stdin.on('data', function(data){
    console.log('stdin:'+data);
});

The result is:

#~$ node test.js
Timeout
kill

But I still need to send ctrl+C to end the program. What am I missing?

On Raspbian, node 0.10.17, omxplayer is a binary (video player).

I tried:

  • Added chmod +x to the app.
  • Launched as root.
  • Paused stdin of the child process. Using all terminate-related signal in the kill command.

I also launched a ps command while the app was running:

2145    bash
2174    node
2175    omxplayer
2176    omxplayer.bin
2177    ps

So omxplayer is a wrapper, who don t kill it's child process when it end, is there any way to get the pid of the wrapped process?

Still biting dust, tried this:

spawn('kill', ['-QUIT', '-$(ps opgid= '+child.pid+')']);

Which I thought would kill all children of omxplayer, I don t know if using spawn like that is wrong or if it's the code that doesn't work.

The last edit I made was the good answer, but had to be edited a bit.

I created a sh file (with execute right) like this:

PID=$1
PGID=$(ps opgid= "$PID")
kill -QUIT -"$PGID"

Which I start like this:

execF('kill.sh', [child.pid], function(){
    console.log('killed');
});

Instead of child.kill.

I'm not sure if it s the best way to do, nor if the code is clean, but it does work.

I'll accept any answer which make it in a cleaner way or, even better, without having to execute a file.

11
  • Raspberry Pi on Raspbian (not sure of the version) , node 0.10.2. I ll try updating node.
    – DrakaSAN
    Commented Sep 9, 2013 at 9:05
  • 1
    Maybe it is something with the privileges. Try running your node script with root access.
    – Krasimir
    Commented Sep 9, 2013 at 9:07
  • Updated node to 0.10.17 and tried to run as root, none worked correctly.
    – DrakaSAN
    Commented Sep 9, 2013 at 9:22
  • 1
    Could this be the problem with omx. Try updating it.
    – user568109
    Commented Sep 9, 2013 at 10:50
  • 3
    I am guessing that the omxplayer executable is a wrapper to a process which outputs the video to screen and it does not close the video process it spawns.
    – user568109
    Commented Sep 9, 2013 at 10:53

12 Answers 12

78

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.

10
  • Tried this too, and commented all "on data", I still need to wait the end of the video.
    – DrakaSAN
    Commented Sep 9, 2013 at 9:46
  • 3
    try child.kill('SIGKILL') and see if that works. child.kill() sends SIGHUP which just tell that the controlling terminal is closed or controlling process is closed. My assumption is SIGKILL would kill it for sure.
    – robinkc
    Commented Sep 9, 2013 at 10:10
  • 1
    Tried SIGHUP, SIGTERM and SIGKILL, the message kill get printed, but the video still play.
    – DrakaSAN
    Commented Sep 9, 2013 at 10:19
  • 3
    Property 'pause' does not exist on type 'Writable'. ts(2339)
    – leonheess
    Commented May 3, 2022 at 20:01
  • 2
    Please use stdin.end() instead of stdin.pause().
    – puchu
    Commented Jul 11, 2023 at 21:42
62

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);
});
6
  • Thank you. This worked for me and seems to be a great alternative.
    – TechnoTim
    Commented Nov 4, 2018 at 14:16
  • 1
    This worked for me whilst child.kill() did not. Using NodeJS v14.15.1, Windows 10
    – turnip
    Commented Dec 10, 2020 at 14:09
  • 2
    I cannot upvote this enough - after wasting 5 hours this is the only solution that worked for me on Windows 7!
    – pishpish
    Commented Jan 29, 2021 at 15:41
  • 1
    This was the only working solution for me. Thanks! Commented Feb 3, 2021 at 11:09
  • Unfortunately this does not work if I want to execute a python script and then terminate it again with kill as described here. I mean the kill from tree-kill.
    – swftowu69
    Commented Apr 11, 2022 at 20:16
12

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);
5

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

3
  • can you explain this?
    – chovy
    Commented Sep 5, 2016 at 0:16
  • It's the natural behaviour of omxplayer. When you launch it in shell, the process is waiting for shortcuts like "q" which will close the program.
    – Superdrac
    Commented Sep 5, 2016 at 7:56
  • 1
    This is very clean solution and works for other programs too. f.stdin.write("q\n"); because some kind of enter is needed.
    – Evil
    Commented Mar 24, 2019 at 3:09
4

In node:16 I was required to destroy() (pause() i not enough) the std channels before sending kill(). Like this:

cmd.stdout.destroy();
cmd.stderr.destroy();
cmd.kill('SIGINT');

See how exec() source code handles kill()

1
  • tHANKS, why does this work and why isn't it documented anywhere? Commented Apr 16 at 16:14
3

You must specify the signal:

child.kill('SIGKILL')

https://nodejs.org/api/child_process.html#child_process_subprocess_kill_signal

3

Please use the following code in the latest lts node (v18).

child.stdin.end();
child.stdout.destroy();
child.stderr.destroy();
child.kill();

It is better to destroy stdout and stderr pipes forcibly before killing process. Otherwise these pipes will still be available after kill during several miliseconds. Some open handler detectors may fail, for example jest:

Jest has detected the following 1 open handle potentially keeping Jest from exiting:

  ●  PIPEWRAP
1

You've spawned a child process which was successfully killed. However, your main thread is still executing, which is why you have to press Ctrl+C.

1
  • 4
    If it only was the main process that was still running, I would be happy, but the child process is obviously still running since the video still play until I send ctrl+C.
    – DrakaSAN
    Commented Sep 9, 2013 at 9:01
1

Finally, I found how to do it without script:

exec('pkill omxplayer', function(err, stdout, stderr){
    if (stdout){console.log('stdout:'+stdout);}
    if (stderr){console.log('stderr:'+stderr);}
    if (err){throw err;}
    //...
}
0

Try to use child_process.execFile() method from here.

The child_process.execFile() function is similar to child_process.exec() except that it does not spawn a shell. Rather, the specified executable file is spawned directly as a new process making it slightly more efficient than child_process.exec().

It works in my case.

0

An alternative that might not exactly suit your use case is setting the detached option to true and ignoring stdin. Then, you can later kill your process using its PID.

const process = child_process.spawn(
  'omxplayer', ['test.mp4'],
  {
    detached: true,
    stdio: ['ignore', 'pipe', 'pipe'],
  }
);

setTimeout(() => {
  child_process.spawnSync(
    'kill', [process.pid.toString()]
  );
}, 1200);
0

Combining and clarifying answers from @Superdrac + @Evil.

If you're running something that has an exit command, just try using that command directly.

For example, most programs take q + enter to exit. So you can run:

child.stdin.write("q\n");

and the process will interpret that the same way, allowing it to clean up itself.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.