diff options
author | Kyle Gunger <kgunger12@gmail.com> | 2024-05-02 00:00:34 -0400 |
---|---|---|
committer | Kyle Gunger <kgunger12@gmail.com> | 2024-05-02 00:00:34 -0400 |
commit | dc9df45dc6578704a367ab6a72842f65b1190f77 (patch) | |
tree | 2ba683aed5e1ba2fa3e72fc9706ad66615cbc336 /src/bind.c | |
parent | aab7fe08faf2aec394174b2ee9782988bfc7fa30 (diff) |
default listen and accept impl
Diffstat (limited to 'src/bind.c')
-rw-r--r-- | src/bind.c | 62 |
1 files changed, 57 insertions, 5 deletions
@@ -1,12 +1,16 @@ #include "osm/bind.h" +#include "osm/utils.h" #include <errno.h> #include <stdio.h> +#include <stdint.h> #include <unistd.h> #include <sys/socket.h> #include <sys/un.h> +#include <threads.h> + #define MAX_ID 0xFFFF @@ -122,9 +126,8 @@ int osm_bind_local(int sockfd, const char *sock_dir) int osm_open_onboard(char *sock_dir) { int sockfd = socket(AF_LOCAL, SOCK_SEQPACKET, 0); - if (sockfd < 0) + if (sockfd == -1) { - perror("socket"); return sockfd; } @@ -140,15 +143,64 @@ int osm_open_onboard(char *sock_dir) if (bound != 0) { - perror("bind"); close(sockfd); - return bound; + return -1; } - + + listen(sockfd, 3); return sockfd; } /** + * Listen for and return connections for a socket + * return - a vector containing all the threads which this function started + */ +Vector osm_listen_and_accept(int sockfd, thrd_start_t callback) +{ + Vector out = vect_init(sizeof(thrd_t)); + thrd_t thread; + + while(1) + { + // Try to accept a connection + errno = 0; + int fd = accept(sockfd, NULL, NULL); + if (fd == -1) + { + if (errno != ECONNABORTED && errno != EINTR) + { + break; + } + else + continue; + } + + // Create and store the connection thread + errno = 0; + int ret = thrd_create(&thread, callback, (void*)(uintptr_t)fd); + if(ret == thrd_success) + { + vect_push(&out, &thread); + } + else + { + if (ret == thrd_error) + { + perror("Error creating thread"); + } + else if (ret == thrd_nomem) + { + fprintf(stderr, "Thread out of memory. Shutting down.\n"); + } + break; + } + + } + + return out; +} + +/** * Bind a new network socket * Should only be called by one process on the machine. * |