gpt4 book ai didi

c - malloc mongoose webserver http post body 并将其传递给线程

转载 作者:太空宇宙 更新时间:2023-11-04 08:07:04 24 4
gpt4 key购买 nike

下面是我正在处理的 mongoose 网络服务器 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。

最佳答案

您可以像这样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 需要一个 void * 作为最后一个参数和任何数据指针可以直接赋值给void *。这同样适用于 struct http_message *hm = (struct http_message *) ev_data; 语句。它可以只是:struct http_message *hm = ev_data;

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

P.S:如果你显示“hm”结构,解释事情会容易得多。

关于c - malloc mongoose webserver http post body 并将其传递给线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42098014/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com