Skip to content

Commit 98649fd

Browse files
OpenSourceStevebnoordhuis
authored andcommitted
doc: add documentation for AtExit hook
Fixes: #999 PR-URL: #1014 Reviewed-By: Ben Noordhuis <[email protected]>
1 parent 6dfca71 commit 98649fd

File tree

1 file changed

+68
-0
lines changed

1 file changed

+68
-0
lines changed

doc/api/addons.markdown

+68
Original file line numberDiff line numberDiff line change
@@ -811,3 +811,71 @@ Test it with:
811811
var result = addon.add(obj1, obj2);
812812

813813
console.log(result); // 30
814+
815+
### AtExit hooks
816+
#### void AtExit(callback, args)
817+
818+
* `callback`: `void (*)(void*)` - A pointer to the function to call at exit.
819+
* `args`: `void*` - A pointer to pass to the callback at exit.
820+
821+
Registers exit hooks that run after the event loop has ended, but before the VM
822+
is killed.
823+
824+
Callbacks are run in last-in, first-out order. AtExit takes two parameters:
825+
a pointer to a callback function to run at exit, and a pointer to untyped
826+
context data to be passed to that callback.
827+
828+
The file `addon.cc` implements AtExit below:
829+
830+
// addon.cc
831+
#undef NDEBUG
832+
#include <assert.h>
833+
#include <stdlib.h>
834+
#include <node.h>
835+
836+
namespace demo {
837+
838+
using node::AtExit;
839+
using v8::HandleScope;
840+
using v8::Isolate;
841+
using v8::Local;
842+
using v8::Object;
843+
844+
static char cookie[] = "yum yum";
845+
static int at_exit_cb1_called = 0;
846+
static int at_exit_cb2_called = 0;
847+
848+
static void at_exit_cb1(void* arg) {
849+
Isolate* isolate = static_cast<Isolate*>(arg);
850+
HandleScope scope(isolate);
851+
Local<Object> obj = Object::New(isolate);
852+
assert(!obj.IsEmpty()); // assert VM is still alive
853+
assert(obj->IsObject());
854+
at_exit_cb1_called++;
855+
}
856+
857+
static void at_exit_cb2(void* arg) {
858+
assert(arg == static_cast<void*>(cookie));
859+
at_exit_cb2_called++;
860+
}
861+
862+
static void sanity_check(void*) {
863+
assert(at_exit_cb1_called == 1);
864+
assert(at_exit_cb2_called == 2);
865+
}
866+
867+
void init(Local<Object> exports) {
868+
AtExit(sanity_check);
869+
AtExit(at_exit_cb2, cookie);
870+
AtExit(at_exit_cb2, cookie);
871+
AtExit(at_exit_cb1, exports->GetIsolate());
872+
}
873+
874+
NODE_MODULE(addon, init);
875+
876+
} // namespace demo
877+
878+
Test in JavaScript by running:
879+
880+
// test.js
881+
var addon = require('./build/Release/addon');

0 commit comments

Comments
 (0)