且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何发送“CTRL+C"Node.js 中的子进程?

更新时间:2022-11-18 12:53:14

kill 仅真正支持 Windows 上的粗鲁进程终止 - Windows 中的应用程序信号模型和 *nix 不兼容.您不能通过标准输入传递 Ctrl+C ,因为它永远不会通过标准输入传递 - 它是控制台子系统的功能(因此您只能在进程具有附加控制台时使用它).它在子进程中创建一个新线程来完成它的工作.

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.

如果您想走完全不受支持的路线,请查看 https://***.com/a/1179124/3032289.

If you want to go the entirely unsupported route, have a look at https://***.com/a/1179124/3032289.

如果你想找到一个中间立场,当然有一种方法可以向你自己发送信号.这也意味着如果您的控制台已连接,您可以将 Ctrl+C 发送到进程.毋庸置疑,这非常棘手 - 您可能想要创建一个本机主机进程,它除了创建控制台并运行您想要运行的实际程序之外什么都不做.然后,您的主机进程将侦听事件,并在发出事件信号时调用 GenerateConsoleCtrlEvent.

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.