搜尋

首頁  >  問答  >  主體

[Node.js]有没有办法使得process捕获到SIGINT信号程序直接退出?

代码:

#!/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)

阿神阿神2856 天前705

全部回覆(2)我來回復

  • 天蓬老师

    天蓬老师2017-04-17 11:15:38

    process.on() 確實無法實作。

    我覺得這是 sync-prompt 自己的問題,這裡面有兩個問題:

    1. 它沒有在std::getline() 之後檢查cin.eof(),如果檢查了就有機會用某種方式通知到呼叫者這個情況,讓呼叫者有機會處理一下。其實不光 Ctrl + C,如果按 Ctrl + D 直接關閉 stdin 也會有同樣的問題,而且 Ctrl + D 根本就不可能透過訊號來捕捉。
    2. sync-prompt 它根本就不應該直接使用 cin,這本身就錯了。你可以試試看,如果先寫了process.stdin.on("end", function() {}) 再執行prompt(),就會發現prompt() 會立即回,此時如果在它的源碼裡面輸出cin.eof() 狀態可以看到這個回傳了true。這是因為這個 on() 呼叫啟用了 stream 模式,關閉了原先的 stdin fd,使得 getline(cin, retval) 這句話徹底不工作了。

    如果還想繼續用它,那麼就把上面的第一條說的回呼機制實現了吧,要不然就完全無解了。


    Update:剛剛看了下sync-prompt 倉庫,發現作者在幾天前加上一個prompt.isEOF() 的函數,這樣終於可以判斷一下是不是因為EOF 退出的了。不過最新的程式碼似乎還沒發佈到 npm registry,要用就需要手動下載程式碼編譯了。

    回覆
    0
  • PHP中文网

    PHP中文网2017-04-17 11:15:38

    setTimeout(function(){
        console.log('你好' + 名字);
        varfruit=prompt('你最喜歡什麼水果?');
        console.log('我也是');
        console.log('這將在您輸入 CTRL+C 後列印');
        進程.退出(0);
    },10);
    

    回覆
    0
  • 取消回覆