0

下面是我正在处理的 mongoose webserver http 事件处理程序的 C 片段:

static void HttpEventHandler(struct mg_connection *nc, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_REQUEST) {
    struct http_message *hm = (struct http_message *) ev_data;
    if (mg_vcmp(&hm->method, "POST") == 0) {
        pthread_t thread_id;
        int rc;
        rc = pthread_create(&thread_id, NULL, thr_func, /* Here I want hm body to be passed after its malloced */);
        if (rc) { /* could not create thread */
            fprintf(stderr, "error: pthread_create, rc: %d\n", rc);
            return EXIT_FAILURE;
        }
    }//if POST
    mg_printf(nc, "HTTP/1.1 200 OK\r\n");
    nc->flags |= MG_F_SEND_AND_CLOSE;
}

}

http post 消息正文,可使用以下语法作为字符串访问:

"%.*s", (int) hm->body.len,hm->body.p

我希望代码示例到 malloc hm->body 并将其传递给上面代码片段中的线程,也很高兴解释如何转换传递的 void *. 如果它很难,那么请 malloc ev_data 或 hm。

4

1 回答 1

2

你会malloc()这样:

    hm->body = malloc(sizeof *(hm->body));
    hm->body.p = "string"; 
    /* The above assigns a string literal. If you need to copy some
       user-defined string then you can instead do:
    hm->body = malloc(size); strcpy(hm->body.p, str); 
    where 'str' is the string you want copy and 'size' is the length of 'str'.
   */
    hm->body.len = strlen(hm->body);

然后将其传递给:

rc = pthread_create(&thread_id, NULL, thr_func, hm->body);

thr_func()您需要将参数转换为任何类型hm->body然后访问它(因为void *不能直接取消引用。)。就像是:

void *thr_func(void *arg)
{
   struct mg_str *hm_body = arg;
   printf("str: %s, len: %zu\n", hm_body->p, hm_body->len);
   ...

   return NULL;
}

无需向void*. pthread_create()API 期望 a作为最后一个参数,void *并且任何数据指针都可以直接分配给void *。这同样适用于struct http_message *hm = (struct http_message *) ev_data;语句。它可以只是:struct http_message *hm = ev_data;

根据“网络服务器”的实现方式,您可能还需要处理线程完成。

PS:如果你显示“hm”结构,解释起来会容易得多。

于 2017-02-07T19:24:52.457 回答