uBus 程序中的分段错误

问题描述 投票:0回答:1

我正在使用OpenWrt提供的ubus消息服务。我用 C 语言编写了一个简单的 ubus 对象。该对象公开了一个不带任何参数的方法,并返回“Hello andwelcome”的响应。 当我在 ubus 上注册该对象并使用命令行调用其方法时,它就可以工作了。但问题是它仅适用于第一次调用或前两次调用。在这两个电话之后,我得到了分段错误。我尝试使用 gdb 进行调试,但它指向 libubus 库中的源文件。我非常怀疑图书馆本身可能有问题。

我也尝试过使用 Valgrind 但它似乎在我的系统上不起作用,而且我似乎也无法解决这个问题。

我在下面附上了源代码、ubus 终端输出、gdb 日志和 Valgrind 错误日志。非常感谢任何和所有的帮助。

源代码

#include <stdio.h>
#include <libubus.h>

// Handler function for the ubus method
static int my_ubus_method(struct ubus_context *ctx, struct ubus_object *obj,
                          struct ubus_request_data *req, const char *method,
                          struct blob_attr *msg)
{
    // Handle the incoming ubus message here
    printf("Received method: %s\n", method);

    // Reply with a simple response
    struct blob_buf b;
    blob_buf_init(&b, 0);
    const char *response_str = "Hello and welcome";
    blobmsg_add_string(&b, "response", response_str);
    
    ubus_send_reply(ctx, req, b.head);

    blob_buf_free(&b);

    return UBUS_STATUS_OK;
}

static const struct blobmsg_policy my_method_policy[] = {};

// Define the ubus methods array
static const struct ubus_method my_ubus_methods[] = {
    UBUS_METHOD("my_method", my_ubus_method, my_method_policy),
};

// Define the ubus object type
static struct ubus_object_type my_ubus_obj_type =
    UBUS_OBJECT_TYPE("my_object", my_ubus_methods);

// Define the ubus object
static struct ubus_object my_ubus_obj = {
    .name = "my_object",
    .type = &my_ubus_obj_type,
    .methods = my_ubus_methods,
    .n_methods = ARRAY_SIZE(my_ubus_methods),
};

int main()
{
    uloop_init();

    struct ubus_context *ctx = ubus_connect(NULL);
    if (!ctx) {
        fprintf(stderr, "Failed to connect to ubus\n");
        return -1;
    }

    ubus_add_uloop(ctx);

    int ret = ubus_add_object(ctx, &my_ubus_obj);
    if (ret) {
        fprintf(stderr, "Failed to add ubus object: %s\n", ubus_strerror(ret));
        ubus_free(ctx);
        return -1;
    }

    printf("Server running...\n");

    uloop_run();
    ubus_free(ctx);

    uloop_done();


    return 0;
}

uBus的终端输出:

gdb 日志

Valgrind 错误日志

c segmentation-fault openwrt
1个回答
0
投票

我找不到导致问题的原因,但我找到了解决方案: 只需将 blob_buf 变量更改为静态变量,代码就会运行:

static struct blob_buf b;

第二个注意事项是,在定义不给出任何参数的 ubus 方法时,我更喜欢使用 UBUS_METHOD_NOARG

// You wont need blobmsg_policy anymore
// static const struct blobmsg_policy my_method_policy[] = {};

// Define the ubus methods array
static const struct ubus_method my_ubus_methods[] = {
    UBUS_METHOD_NOARG("my_method", my_ubus_method),
};
© www.soinside.com 2019 - 2024. All rights reserved.