Nodejs Addons uv_queue_work segmentation fault

2019-05-21 08:12发布

I'm trying to create a very little nodejs addons example. My c++ code is this:

void __sleep(uv_work_t* req) {
    usleep(1000 * 1000 * 5); // = 5seconds
}

void after(uv_work_t *handle, int status) {
    printf("After\n");
}

Handle<Value> foo(const Arguments& args) {
    HandleScope scope;
    uv_loop_t *loop = uv_default_loop();
    uv_work_t req;
    uv_queue_work(loop, &req, __sleep, after);
    return scope.Close(Undefined());
}

void InitAll(Handle<Object> exports, Handle<Object> module) {
    NODE_SET_METHOD(exports, "foo", foo);
}

NODE_MODULE("myModule", InitAll)

In js, this:

console.log(myModule);
myModule.foo();
console.log("started sleeping...");

When i call myModule.foo function the process terminates with a segmentation fault.

I have tried to add uv_run(loop, UV_RUN_DEFAULT) but this blocks the main thread.

Where did I go wrong? Thanks

1条回答
相关推荐>>
2楼-- · 2019-05-21 08:53

The problem is that req is allocated on stack and is freed when foo returns. You need to allocate it on heap (using new or malloc) and free it manually when you are done (for example, in after callback)

查看更多
登录 后发表回答