为什么使用paho.mqtt.c发送此消息会导致分段错误?

时间:2017-11-30 13:37:21

标签: c segmentation-fault mqtt paho cjson

我正在尝试使用MQTT协议发送特定的消息类型。我正在使用paho.mqtt.c库,我的代理是RabbitMQ 3.6.12,运行Erlang 20.0。我正在使用运行CentOS 6.9的虚拟机。 我首先尝试通过为我的特定消息类型创建一个结构,然后在提出这个问题之前,我还尝试使用JSON创建我的特定消息类型。我安装了cJSON(来自here)。

以下是我使用cJSON的全部代码:

pubframe.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "../tools.c"
#include <cjson/cJSON.h>

#define ADDRESS      "tcp://localhost:1883"
#define CLIENTID     "MY_PUB"
#define TOPIC        "MQTT/Test"

int main(int argc, char* argv[])
{   

        frame1 test = {42,"test"};

        cJSON* frm = NULL;
        frm = cJSON_CreateObject();

        cJSON_AddNumberToObject(frm,"entier",test.E);
        cJSON_AddStringToObject(frm,"string",test.S);

        print_frame1(frm);

        int i = cJSON_GetArraySize(frm);
        printf("number of items in frame : %d\n",i);
        cJSON* entier = NULL;
        entier = cJSON_GetObjectItem(frm,"entier");
        char* pt = cJSON_Print(entier);
        printf("entier : %s\n",pt);
        cJSON* str = NULL;
        str = cJSON_GetObjectItem(frm,"string");
        char* st = cJSON_Print(str);
        printf("string : %s\n",st);

        printf("size of message : %d\n",sizeof(cJSON));

        MQTTClient publisher;
        MQTTClient_connectOptions connexion = MQTTClient_connectOptions_initializer;

        MQTTClient_message msg = msg_creation(frm,sizeof(cJSON),0,0);
    MQTTClient_deliveryToken token;
        int rc;
        MQTTClient_create(&publisher, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    connexion.cleansession = 1;
        MQTTClient_setCallbacks(publisher, NULL, connlost, frame_json_arrvd, NULL);
        if ((rc = MQTTClient_connect(publisher,&connexion)) != MQTTCLIENT_SUCCESS)
        {
            printf("Failed to connect, return code %d\n", rc);
        }
        MQTTClient_publishMessage(publisher, TOPIC,&msg,NULL);
        printf("Message sent!\n");
        cJSON_Delete(frm);
        MQTTClient_disconnect(publisher,10000);
        MQTTClient_destroy(&publisher);
        return rc;
}

subframe.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "../tools.c"
#include <cjson/cJSON.h>


#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ClientID"
#define TOPIC       "MQTT/Test"
#define QOS         0
#define TIMEOUT     10000L

int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;
    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    MQTTClient_setCallbacks(client, NULL, connlost, frame_json_arrvd, NULL);
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);
    do
    {
        ch = getchar();
    } while(ch!='Q' && ch != 'q');
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}

tools.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <cjson/cJSON.h>
#include "MQTTClient.h"

int compteur;

// message frames

typedef struct frame1
{
    int E;
    char* S;
} frame1;

void print_frame1bis(frame1* F)
{
        printf("     %s\n",F->S);
        printf("     %d\n",F->E);
}

void print_frame1(cJSON* frame1)
{
    char * str = cJSON_Print(frame1);
    printf("%s\n",str);
}

int frame_json_arrvd(void* context, char* topicName, int topicLen, MQTTClient_message* msg)
{

        cJSON* payload_ptr = NULL;

        printf("size of message : %d\n",sizeof(msg->payload));

        int j = cJSON_GetArraySize(msg->payload);
        printf("ok\n");
        printf("number of items in frame : %d\n",j);

        payload_ptr = cJSON_CreateObject();
        payload_ptr = msg->payload;

        int i = cJSON_GetArraySize(payload_ptr);
        printf("number of items in frame : %d\n",i);

        print_frame1(payload_ptr);

        cJSON_Delete(payload_ptr);
        MQTTClient_freeMessage(&msg);
        MQTTClient_free(topicName);
        return 1;
}

// in case connexion is lost

void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);
}


// create message

MQTTClient_message msg_creation(void* payload, int length, int qos, int retained)
{
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = payload;
    pubmsg.payloadlen = length;
    pubmsg.qos = qos;
    pubmsg.retained = retained;
    return pubmsg;
}

订阅者的出局是

Subscribing to topic MQTT/Test
for client ClientID using QoS0

Press Q<Enter> to quit

size of message : 8
Segmentation fault (core dumped)

因此,当订户尝试获取项目数时,订阅者就会崩溃,因此似乎未正确收到该消息。

这是我运行gdb时得到的,不确定它是否有帮助。

Program terminated with signal 11, Segmentation fault.
#0  0x00007f4e49a8b63e in cJSON_GetArraySize () from /usr/lib64/libcjson.so.1
(gdb) bt
#0  0x00007f4e49a8b63e in cJSON_GetArraySize () from /usr/lib64/libcjson.so.1
#1  0x00000000004010c9 in frame_json_arrvd (context=0x0,
    topicName=0x7f4e440009e4 "MQTT/Test", topicLen=0, msg=0x7f4e44000bb4)
    at ../tools.c:110
#2  0x00007f4e49c962a5 in MQTTClient_run (n=<value optimized out>)
    at src/MQTTClient.c:604
#3  0x000000378b807aa1 in start_thread (arg=0x7f4e49a83700) at pthread_create.c:301
#4  0x000000378b4e8bcd in clone () at ../sysdeps/unix/sysv/linux/x86_64/clone.S:115

发布商的输出是

{
        "entier":       42,
        "string":       "test"
}
number of items in frame : 2
entier : 42
string : "test"
size of message : 64
Message sent!

所以看起来消息是正确创建的。

我最近刚看了cJSON,所以我会继续调查,以防我使用它错了,但任何帮助都会受到赞赏。 我试图按照评论中的建议缩小范围,但我看不到我能做什么,因为它一旦尝试访问消息的有效负载就会崩溃。

请记住,我只是一名不超过一年的计算机科学经验的学生。此外,英语不是我的母语,我希望我能够清楚地解释自己。

1 个答案:

答案 0 :(得分:0)

问题解决了(有点)

我只是将整个消息帧作为字符串发送并在msgarrvd函数中解析它:

pubframe.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "../tools.c"
#include <cjson/cJSON.h>

#define ADDRESS      "tcp://localhost:1883"
#define CLIENTID     "MY_PUB"
#define TOPIC        "MQTT/Test"

volatile MQTTClient_deliveryToken deliveredtoken;
void delivered(void *context, MQTTClient_deliveryToken dt)
{
    printf("Message with token value %d delivery confirmed\n", dt);
    deliveredtoken = dt;
}

int main(int argc, char* argv[])
{   

    char* test = "{\"string\" : \"whatever\", \"entier\" : 42}";

    MQTTClient publisher;
    MQTTClient_connectOptions connexion = MQTTClient_connectOptions_initializer;

    MQTTClient_message msg = msg_creation(test,strlen(test),0,0);

    int rc;
    MQTTClient_create(&publisher, ADDRESS, CLIENTID, MQTTCLIENT_PERSISTENCE_NONE, NULL);
    connexion.cleansession = 1;
    MQTTClient_setCallbacks(publisher, NULL, connlost, frame_test_arrvd, NULL);
    if ((rc = MQTTClient_connect(publisher,&connexion)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
    }
    MQTTClient_publishMessage(publisher, TOPIC,&msg,&token);
    printf("Message sent!\n");
    cJSON_Delete(frm);
    MQTTClient_disconnect(publisher,10000);
    MQTTClient_destroy(&publisher);
    return rc;
}

tools.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>
#include <sys/time.h>
#include <cjson/cJSON.h>
#include "MQTTClient.h"

// message frames

void print_frame1(cJSON* frame1)
{
    char * str = cJSON_Print(frame1);
    printf("%s\n",str);
}

int frame_test_arrvd(void* context, char* topicName, int topicLen, MQTTClient_message* msg)
{
    printf("message original : %s\n",msg->payload);
    cJSON* payload_ptr = cJSON_Parse(msg->payload);

    print_frame1(payload_ptr);
    int i = cJSON_GetArraySize(payload_ptr);
    printf("number of items in frame : %d\n",i);
    cJSON* entier = NULL;
    entier = cJSON_GetObjectItem(payload_ptr,"entier");
    char* pt = cJSON_Print(entier);
    printf("entier : %s\n",pt);
    cJSON* str = NULL;
    str = cJSON_GetObjectItem(payload_ptr,"string");
    char* st = cJSON_Print(str);
    printf("string : %s\n",st);

    cJSON_Delete(payload_ptr);

    MQTTClient_freeMessage(&msg);
    MQTTClient_free(topicName);
    return 1;
}

// in case connexion is lost

void connlost(void *context, char *cause)
{
    printf("\nConnection lost\n");
    printf("     cause: %s\n", cause);
}


// create message

MQTTClient_message msg_creation(void* payload, int length, int qos, int retained)
{
    MQTTClient_message pubmsg = MQTTClient_message_initializer;
    pubmsg.payload = payload;
    pubmsg.payloadlen = length;
    pubmsg.qos = qos;
    pubmsg.retained = retained;
    return pubmsg;
}

subframe.c:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include "MQTTClient.h"
#include "../tools.c"
#include <cjson/cJSON.h>


#define ADDRESS     "tcp://localhost:1883"
#define CLIENTID    "ClientID"
#define TOPIC       "MQTT/Test"
#define QOS         0
#define TIMEOUT     10000L

int main(int argc, char* argv[])
{
    MQTTClient client;
    MQTTClient_connectOptions conn_opts = MQTTClient_connectOptions_initializer;
    int rc;
    int ch;
    MQTTClient_create(&client, ADDRESS, CLIENTID,
        MQTTCLIENT_PERSISTENCE_NONE, NULL);
    conn_opts.keepAliveInterval = 20;
    conn_opts.cleansession = 1;
    MQTTClient_setCallbacks(client, NULL, connlost, frame_test_arrvd, NULL);
    if ((rc = MQTTClient_connect(client, &conn_opts)) != MQTTCLIENT_SUCCESS)
    {
        printf("Failed to connect, return code %d\n", rc);
        exit(EXIT_FAILURE);
    }
    printf("Subscribing to topic %s\nfor client %s using QoS%d\n\n"
           "Press Q<Enter> to quit\n\n", TOPIC, CLIENTID, QOS);
    MQTTClient_subscribe(client, TOPIC, QOS);
    do
    {
        ch = getchar();
    } while(ch!='Q' && ch != 'q');
    MQTTClient_disconnect(client, 10000);
    MQTTClient_destroy(&client);
    return rc;
}

这还不理想,因为我仍然想创建特定类型的消息,而且我还没有发现导致分段错误的原因,但它以这种方式完美运行。

<强>更新

我找到了一种创建特定类型消息的方法,仍然将它们作为字符串发送到msgarrvd函数中解析它们,我刚刚创建了一个函数cJSON_ToString来将cJSON *对象转换为字符串,这样我就可以创建一个cJOSN从我想要的任何结构中,然后将其转换为字符串以发送它。