update C
snipplets
This commit is contained in:
2
code/C/Web/ulfius-server/.editorconfig
Normal file
2
code/C/Web/ulfius-server/.editorconfig
Normal file
@ -0,0 +1,2 @@
|
||||
[{*.c,*.h}]
|
||||
indent_size = unset
|
6
code/C/Web/ulfius-server/.gitignore
vendored
Normal file
6
code/C/Web/ulfius-server/.gitignore
vendored
Normal file
@ -0,0 +1,6 @@
|
||||
orcania/
|
||||
ulfius/
|
||||
|
||||
*.a
|
||||
|
||||
rest
|
7
code/C/Web/ulfius-server/Makefile
Normal file
7
code/C/Web/ulfius-server/Makefile
Normal file
@ -0,0 +1,7 @@
|
||||
CC = clang
|
||||
|
||||
all:
|
||||
$(CC) -std=c99 -Wall -O3 -o rest main.c -lulfius -lorcania
|
||||
|
||||
tcc:
|
||||
tcc -O3 -I./ulfius/include -I./orcania/include -o rest main.c libulfius.2.7.13.a liborcania.2.3.2.a -lyder -lgnutls -lz -ljansson -lmicrohttpd -lcurl
|
16
code/C/Web/ulfius-server/README.md
Normal file
16
code/C/Web/ulfius-server/README.md
Normal file
@ -0,0 +1,16 @@
|
||||
REST API
|
||||
--------
|
||||
|
||||
* `http://localhost:8000/api/param/:name` - возвращает `:name`
|
||||
* `http://localhost:8000/api/param/quit` - завершит выполнение программы
|
||||
|
||||
Зависимости
|
||||
-----------
|
||||
|
||||
* [ulfius](https://github.com/babelouest/ulfius)
|
||||
* [orcania](https://github.com/babelouest/orcania)
|
||||
|
||||
```sh
|
||||
ar rcs libulfius.2.7.13.a ulfius.o u_map.o u_request.o u_response.o u_send_request.o u_websocket.o yuarel.o
|
||||
ar rcs liborcania.2.3.2.a orcania.o memory.o base64.o
|
||||
```
|
26
code/C/Web/ulfius-server/main.c
Normal file
26
code/C/Web/ulfius-server/main.c
Normal file
@ -0,0 +1,26 @@
|
||||
#include <sys/socket.h>
|
||||
#include <arpa/inet.h>
|
||||
#include <netinet/in.h>
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
#include <string.h>
|
||||
#include <pthread.h>
|
||||
#include <ulfius.h>
|
||||
|
||||
#include <stdatomic.h>
|
||||
|
||||
#include "utils.h"
|
||||
#include "server.h"
|
||||
|
||||
int main(int argc, char **argv) {
|
||||
// создаём отдельный поток, в котором запускаем сервер
|
||||
pthread_t tid;
|
||||
pthread_create(&tid, NULL, thread_server, (void *)&tid);
|
||||
|
||||
// while (true) {
|
||||
// }
|
||||
|
||||
pthread_exit(NULL);
|
||||
|
||||
return 0;
|
||||
}
|
BIN
code/C/Web/ulfius-server/qa/answer.png
Normal file
BIN
code/C/Web/ulfius-server/qa/answer.png
Normal file
Binary file not shown.
After Width: | Height: | Size: 78 KiB |
61
code/C/Web/ulfius-server/qa/question.md
Normal file
61
code/C/Web/ulfius-server/qa/question.md
Normal file
@ -0,0 +1,61 @@
|
||||
Помогите с проблемой. Не завершается `while` цикл при изменении переменной `running`.
|
||||
|
||||
```
|
||||
while (running) {
|
||||
// loop
|
||||
}
|
||||
```
|
||||
|
||||
Использую библиотеку `ulfius` для реализации REST API сервера.
|
||||
Есть функция `thread_server()`, которую из `main()` запускаю в отдельном потоке,
|
||||
в которой запускается `ulfius` сервер.
|
||||
|
||||
```
|
||||
pthread_t tid;
|
||||
pthread_create(&tid, NULL, thread_server, (void *)&tid);
|
||||
```
|
||||
|
||||
Сервер запускаю следующим образом:
|
||||
```
|
||||
int ret;
|
||||
ret = ulfius_start_framework(&instance);
|
||||
|
||||
if (ret == U_OK) {
|
||||
printf("Server started at %d.\n", PORT);
|
||||
} else {
|
||||
printf("Error starting server as %d port.\n", PORT);
|
||||
}
|
||||
|
||||
while (running) {
|
||||
printf("\r%b", running);
|
||||
}
|
||||
printf("Server halt.\n");
|
||||
|
||||
ulfius_stop_framework(&instance);
|
||||
ulfius_clean_instance(&instance);
|
||||
```
|
||||
|
||||
`running` - глобальная переменная типа `bool`.
|
||||
|
||||
В документации к библиотеке, чтобы сервер не схлопывался используется следующий код.
|
||||
```
|
||||
if (ret == U_OK) {
|
||||
getchar();
|
||||
}
|
||||
```
|
||||
|
||||
Есть callback функция, которая вызывается при обращении к API,
|
||||
в которой я проверяю отправленное пользователем значение, и если оно равняется `quit`
|
||||
присваиваю переменной `running` значение `false`, чтобы сервер закрылся.
|
||||
|
||||
Если из цикла `while (running) { printf("\r%b", running); }` убрать `printf()`,
|
||||
либо выполнять другие операции, например присвоение `a = 1;` то сервер не закрывается,
|
||||
хотя значение `running` равняется `0`.
|
||||
|
||||
Я пишу утилиту для внутенного использования, которая общается с Arduino платой
|
||||
посредством библиотеки `libserialport` и в цикле читает данные.
|
||||
|
||||
Хочу, чтобы утилита по REST получала данные и отправляла их на плату,
|
||||
но не получается реализовать нормальное завершение программы, потому что сервер не умирает.
|
||||
|
||||
**OS:** Linux
|
75
code/C/Web/ulfius-server/server.h
Normal file
75
code/C/Web/ulfius-server/server.h
Normal file
@ -0,0 +1,75 @@
|
||||
atomic_bool running = true;
|
||||
|
||||
#define PORT 8000
|
||||
#define PREFIX "/api"
|
||||
|
||||
int callback_default(const struct _u_request *request,
|
||||
struct _u_response *response, void *user_data);
|
||||
int callback_all_test_foo(const struct _u_request *request,
|
||||
struct _u_response *response, void *user_data);
|
||||
|
||||
void *thread_server(void *vargp) {
|
||||
int ret;
|
||||
struct _u_instance instance;
|
||||
|
||||
if (ulfius_init_instance(&instance, PORT, NULL, NULL) != U_OK) {
|
||||
exit(1);
|
||||
}
|
||||
|
||||
instance.max_post_body_size = 1024;
|
||||
|
||||
ulfius_add_endpoint_by_val(&instance, "GET", PREFIX, "/param/:name", 0,
|
||||
&callback_all_test_foo, "user data 1");
|
||||
ulfius_add_endpoint_by_val(&instance, "POST", PREFIX, "/param/:name", 0,
|
||||
&callback_all_test_foo, "user data 2");
|
||||
|
||||
ulfius_set_default_endpoint(&instance, &callback_default, NULL);
|
||||
|
||||
ret = ulfius_start_framework(&instance);
|
||||
|
||||
if (ret == U_OK) {
|
||||
printf("Server started at %d.\n", PORT);
|
||||
} else {
|
||||
printf("Error starting server as %d port.\n", PORT);
|
||||
}
|
||||
|
||||
while (running) {
|
||||
}
|
||||
printf("Server halt.\n");
|
||||
|
||||
ulfius_stop_framework(&instance);
|
||||
ulfius_clean_instance(&instance);
|
||||
}
|
||||
|
||||
int callback_default(const struct _u_request *request,
|
||||
struct _u_response *response, void *user_data) {
|
||||
(void)(request);
|
||||
(void)(user_data);
|
||||
ulfius_set_string_body_response(response, 404,
|
||||
"Page not found, do what you want");
|
||||
|
||||
return U_CALLBACK_CONTINUE;
|
||||
}
|
||||
|
||||
int callback_all_test_foo(const struct _u_request *request,
|
||||
struct _u_response *response, void *user_data) {
|
||||
// url_params = request->map_url
|
||||
// post_params = request->map_post_body
|
||||
|
||||
const char **keys, *value;
|
||||
keys = u_map_enum_keys(request->map_url);
|
||||
value = u_map_get(request->map_url, keys[0]);
|
||||
|
||||
if (strcmp("quit", value) == 0) {
|
||||
running = false;
|
||||
}
|
||||
|
||||
char *response_body = msprintf("Your %s is %s\n", keys[0], value);
|
||||
|
||||
print_to_terminal(response_body);
|
||||
ulfius_set_string_body_response(response, 200, response_body);
|
||||
|
||||
o_free(response_body);
|
||||
|
||||
return U_CALLBACK_CONTINUE;
|
||||
}
|
1
code/C/Web/ulfius-server/utils.h
Normal file
1
code/C/Web/ulfius-server/utils.h
Normal file
@ -0,0 +1 @@
|
||||
void print_to_terminal(char *text) { printf("%s", text); }
|
Reference in New Issue
Block a user