Nodejs Addons uv_queue_work分段故障 [英] Nodejs Addons uv_queue_work segmentation fault

查看:501
本文介绍了Nodejs Addons uv_queue_work分段故障的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个非常小的nodejs插件示例。
我的c ++代码是这样:

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)

在js中,这:

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

当我调用 myModule.foo

我尝试添加 uv_run(loop,UV_RUN_DEFAULT),但这会阻止主线程。

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

我在哪里错了?
感谢

Where did I go wrong? Thanks

推荐答案

问题是 req 并且在 foo 返回时释放。你需要在堆上分配它(使用 new malloc ),并在完成后手动释放,之后回调)

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)

这篇关于Nodejs Addons uv_queue_work分段故障的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆