[Node.js]有没有办法使得process捕获到SIGINT信号程序直接退出?
阿神
阿神 2017-04-17 11:13:38
0
2
663

代码:

#!/usr/bin/env node
// npm install sync-prompt
var prompt = require('sync-prompt').prompt;

var name = prompt('what is your name? ');
console.log('Hello ' + name);
var fruit = prompt('what is your favorite fruit? ');
console.log('me too');
process.on('SIGINT', function(){
    process.exit(0);
});
console.log('this would be print after you type CTRL+C');
process.exit(0);

输出结果:

[honwhy@localhost nodejs]$ ./example.js 
what is your name? honey
Hello honey
what is your favorite fruit? ^Cme too
this would be print after you type CTRL+C

由于process.on是异步执行的,所以在程序退出前还会输出me toothis would be...等语句。
有没有办法在程序(process)捕获到SIGINT后同步方式执行,直接退出程序呢?

UPDATE
对原作者的模块源码做了一点修改了,提交了pull request,不过貌似提交失败了,等待结果中。issue地址:https://github.com/shovon/sync-prompt/pull/9
(2014年7月7日 18:39:17)

阿神
阿神

闭关修行中......

reply all(2)
Peter_Zhu

It is indeed impossible to achieve with process.on().

I think this is sync-prompt's own problem. There are two problems here:

  1. It does not check cin.eof() after std::getline(). If checked, there would be a chance to notify the caller of this situation in some way. , giving the caller a chance to process it. In fact, not only Ctrl + C, if you press Ctrl + D to close stdin directly, you will have the same problem, and Ctrl + D is simply impossible to capture through signals.
  2. sync-prompt It should not use cin directly at all, which is wrong in itself. You can try it. If you write process.stdin.on("end", function() {}) first and then execute prompt(), you will find that prompt() will return immediately. At this time, if the cin.eof() status is output in its source code, you can see that this returns true. This is because this on() call enables stream mode and closes the original stdin fd, causing the sentence getline(cin, retval) to not work at all.

If you still want to continue using it, then implement the callback mechanism mentioned in the first item above, otherwise there will be no solution at all.


Update: I just took a look at the sync-prompt warehouse and found that the author added a prompt.isEOF() function a few days ago, so I can finally make a judgment. Did you quit because of EOF? However, it seems that the latest code has not yet been released to the npm registry. If you want to use it, you need to manually download the code and compile it.

Ty80
setTimeout(function(){
    console.log('Hello ' + name);
    var fruit = prompt('what is your favorite fruit? ');
    console.log('me too');
    console.log('this would be print after you type CTRL+C');
    process.exit(0);
},10);
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template