Permalink
Browse files

process, feat: support Event beforeExit.

  • Loading branch information...
xicilion committed Oct 16, 2017
1 parent b6ec655 commit 08cf7066e4353c3d3c7e2903130a29e262795d9c
Showing with 62 additions and 1 deletion.
  1. +10 −1 fibjs/src/coroutine/Fiber.cpp
  2. +12 −0 idl/zh-cn/process.idl
  3. +2 −0 test/process/exec13.js
  4. +2 −0 test/process/exec14.js
  5. +18 −0 test/process/exec15.js
  6. +18 −0 test/process_test.js
@@ -7,6 +7,7 @@
#include "object.h"
#include "Fiber.h"
#include "Trigger.h"
#include "ifs/os.h"
#include "ifs/process.h"
@@ -73,8 +74,16 @@ void JSFiber::fiber_proc(void* p)
if (isolate->m_pendding.dec() == 0)
if (isolate->m_id == 1) {
v8::HandleScope handle_scope(isolate->m_isolate);
JSFiber::scope s;
process_base::exit(hr);
JSTrigger t(isolate->m_isolate, process_base::class_info().getModule(isolate));
v8::Local<v8::Value> code = v8::Number::New(isolate->m_isolate, isolate->m_exitCode);
bool r;
isolate->m_pendding.inc();
t._emit("beforeExit", &code, 1, r);
if (isolate->m_pendding.dec() == 0)
process_base::exit(hr);
}
}
View
@@ -4,6 +4,18 @@
```JavaScript
var process = require('process');
```
## 进程事件
process 模块对象是 EventEmitter 的实例,可以通过注册事件监听器响应进程级别的事件。
### beforeExit
**当 fibjs 的任务已经为空,并且没有额外的工作被添加进来,事件 `beforeExit` 会被触发**
```JavaScript
process.on('beforeExit', exitCode => {});
```
正常情况下,如果没有额外的工作被添加到任务队列,fibjs 进程会结束。但是如果 `beforeExit` 事件绑定的监听器的回调函数中,启动了一个新的任务,比如开启一个 fiber,那么 fibjs 进程会继续运行。
`process.exitCode` 作为唯一的参数值传递给 `beforeExit` 事件监听器的回调函数。如果进程由于显式的原因而将要终止,例如直接调用 `process.exit` 或抛出未捕获的异常,`beforeExit`事件不会被触发。
*/
module process : EventEmitter
{
View
@@ -0,0 +1,2 @@
process.exitCode = 100;
process.exit();
View
@@ -0,0 +1,2 @@
process.exitCode = 100;
process.exit(101);
View
@@ -0,0 +1,18 @@
process.exitCode = 101;
process.on('beforeExit', exitCode => {
console.log('beforeExit', exitCode);
});
var once = true;
process.on('beforeExit', exitCode => {
console.log('other beforeExit', exitCode);
if (once) {
once = false;
setTimeout(() => {
console.log("new work", exitCode);
}, 10);
}
});
View
@@ -54,6 +54,11 @@ describe('process', () => {
assert.equal(process.run(cmd, [path.join(__dirname, 'process', 'exec.js')]), 100);
});
it("exitCode", () => {
assert.equal(process.run(cmd, [path.join(__dirname, 'process', 'exec13.js')]), 100);
assert.equal(process.run(cmd, [path.join(__dirname, 'process', 'exec14.js')]), 101);
});
xit("run throw error", () => {
assert.throws(() => {
process.run("not_exists_exec_file");
@@ -212,6 +217,19 @@ describe('process', () => {
assert.equal(old, process.umask());
});
}
describe("Event", () => {
it("beforeExit", () => {
var bs = process.open(cmd, [path.join(__dirname, 'process', 'exec15.js')]);
assert.deepEqual(bs.readLines(), [
"beforeExit 101",
"other beforeExit 101",
"new work 101",
"beforeExit 101",
"other beforeExit 101"
]);
});
});
});
repl && test.run(console.DEBUG);

0 comments on commit 08cf706

Please sign in to comment.