How to send "CTRL+C" to child process in Node.js?
Asked Answered
V

1

4

I tried to spawn child process - vvp (https://linux.die.net/man/1/vvp). At the certain time, I need to send CTRL+C to that process. I am expecting that simulation will be interrupted and I get the interactive prompt. And after that I can continue the simulation by send command to the child process. So, I tried something like this:

var child = require('child_process');
var fs = require('fs');
var vcdGen = child.spawn('vvp', ['qqq'], {});

vcdGen.stdout.on('data', function(data) {
  console.log(data.toString())
});

setTimeout(function() {
  vcdGen.kill('SIGINT');
}, 400);

In that case, a child process was stopped. I also tried vcdGen.stdin.write('\x03') instead of vcdGen.kill('SIGINT'); but it isn't work.

Maybe it's because of Windows? Is there any way to achieve the same behaviour as I got in cmd?

Venereal answered 1/2, 2017 at 9:53 Comment(2)
Added Windows tag (critical to the question) and thus cmd not needed (and spawn is more specific than child-process)Laurielaurier
@Laurielaurier Not to mention that cmd isn't involved at all - it's just a command processor, and has nothing to do with the console subsystem (apart from being a console application like any other, of course).Whoop
W
6

kill only really supports a rude process kill on Windows - the application signal model in Windows and *nix isn't compatible. You can't pass Ctrl+C through standard input, because it never comes through standard input - it's a function of the console subsystem (and thus you can only use it if the process has an attached console). It creates a new thread in the child process to do its work.

There's no supported way to do this programmatically. It's a feature for the user, not the applications. The only way to do this would be to do the same thing the console subsystem does - create a new thread in the target application and let it do the signalling. But the best way would be to simply use coöperative signalling instead - though that of course requires you to change the target application to understand the signal.

If you want to go the entirely unsupported route, have a look at https://mcmap.net/q/110678/-can-i-send-a-ctrl-c-sigint-to-an-application-on-windows.

If you want to find a middle ground, there's a way to send a signal to yourself, of course. Which also means that you can send Ctrl+C to a process if your consoles are attached. Needless to say, this is very tricky - you'd probably want to create a native host process that does nothing but create a console and run the actual program you want to run. Your host process would then listen for an event, and when the event is signalled, call GenerateConsoleCtrlEvent.

Whoop answered 1/2, 2017 at 10:9 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.