Nodejs Addons uv_queue_work segmentation fault

大憨熊 提交于 2019-12-08 00:21:35

问题


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:


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)



来源:https://stackoverflow.com/questions/29880486/nodejs-addons-uv-queue-work-segmentation-fault

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!