diff options
author | Egor Tensin <Egor.Tensin@gmail.com> | 2023-05-13 10:58:41 +0200 |
---|---|---|
committer | Egor Tensin <Egor.Tensin@gmail.com> | 2023-05-13 11:37:46 +0200 |
commit | cd917f48454875ad6b7fc69455281d72760c44ee (patch) | |
tree | 70a7a43fe43b7f893468f9120def5513774a242c /src/tcp_server.c | |
parent | add command module to handle request-response communications (diff) | |
download | cimple-cd917f48454875ad6b7fc69455281d72760c44ee.tar.gz cimple-cd917f48454875ad6b7fc69455281d72760c44ee.zip |
best practices & coding style fixes
* I don't really need to declare all variables at the top of the
function anymore.
* Default-initialize variables more.
* Don't set the output parameter until the object is completely
constructed.
Diffstat (limited to '')
-rw-r--r-- | src/tcp_server.c | 37 |
1 files changed, 18 insertions, 19 deletions
diff --git a/src/tcp_server.c b/src/tcp_server.c index acd3320..25a74a7 100644 --- a/src/tcp_server.c +++ b/src/tcp_server.c @@ -21,21 +21,20 @@ struct tcp_server { int tcp_server_create(struct tcp_server **_server, const char *port) { - struct tcp_server *server; int ret = 0; - *_server = malloc(sizeof(struct tcp_server)); - if (!*_server) { + struct tcp_server *server = malloc(sizeof(struct tcp_server)); + if (!server) { log_errno("malloc"); return -1; } - server = *_server; ret = net_bind(port); if (ret < 0) goto free; server->fd = ret; + *_server = server; return ret; free: @@ -75,29 +74,29 @@ close: int tcp_server_accept(const struct tcp_server *server, tcp_server_conn_handler handler, void *arg) { - struct child_context *ctx; pthread_attr_t child_attr; sigset_t old_mask; pthread_t child; - int conn_fd, ret = 0; - - ret = net_accept(server->fd); - if (ret < 0) - return ret; - conn_fd = ret; + int ret = 0; - ctx = malloc(sizeof(*ctx)); + struct child_context *ctx = calloc(1, sizeof(*ctx)); if (!ctx) { log_errno("malloc"); - ret = -1; - goto close_conn; + return -1; } - *ctx = (struct child_context){conn_fd, handler, arg}; + + ctx->handler = handler; + ctx->arg = arg; + + ret = net_accept(server->fd); + if (ret < 0) + goto free_ctx; + ctx->fd = ret; ret = pthread_attr_init(&child_attr); if (ret) { pthread_errno(ret, "pthread_attr_init"); - goto free_ctx; + goto close_conn; } ret = pthread_attr_setdetachstate(&child_attr, PTHREAD_CREATE_DETACHED); @@ -128,11 +127,11 @@ restore_mask: destroy_attr: pthread_errno_if(pthread_attr_destroy(&child_attr), "pthread_attr_destroy"); +close_conn: + log_errno_if(close(ctx->fd), "close"); + free_ctx: free(ctx); -close_conn: - log_errno_if(close(conn_fd), "close"); - return ret; } |