get unix socket path from argv

This commit is contained in:
hippoz 2022-09-17 21:23:16 +03:00
parent b137de75f5
commit ddfa02eb7b
No known key found for this signature in database
GPG key ID: 7C52899193467641

28
main.c
View file

@ -14,8 +14,6 @@
#define BACKLOG 10 #define BACKLOG 10
#define DIE(info) ({perror((info)); exit(EXIT_FAILURE);}) #define DIE(info) ({perror((info)); exit(EXIT_FAILURE);})
static const char *socket_path = "/tmp/plumb-unix0";
struct client { struct client {
int fd; int fd;
}; };
@ -175,7 +173,7 @@ void server_free(struct server *s)
free(s); free(s);
} }
struct server *server_create() struct server *server_create(const char *socket_path)
{ {
struct server *s = malloc(sizeof(struct server)); struct server *s = malloc(sizeof(struct server));
if (s == NULL) { if (s == NULL) {
@ -195,6 +193,8 @@ struct server *server_create()
name.sun_family = AF_UNIX; name.sun_family = AF_UNIX;
strncpy(name.sun_path, socket_path, sizeof(name.sun_path) - 1); strncpy(name.sun_path, socket_path, sizeof(name.sun_path) - 1);
unlink(socket_path);
if (bind(s->sock_fd, (const struct sockaddr *)&name, sizeof(name)) == -1) { if (bind(s->sock_fd, (const struct sockaddr *)&name, sizeof(name)) == -1) {
free(s); free(s);
close(s->sock_fd); close(s->sock_fd);
@ -300,14 +300,32 @@ int server_turn(struct server *s)
return 0; return 0;
} }
int main()
const char *arg_shift(int *argc, char ***argv) {
if (*argc < 1)
return NULL;
const char *result = *argv[0];
*argc -= 1;
*argv += 1;
return result;
}
int main(int argc, char *argv[])
{ {
struct server *srv = server_create(); arg_shift(&argc, &argv);
const char *socket_path = arg_shift(&argc, &argv);
socket_path = socket_path == NULL ? "/tmp/duct-unix0" : socket_path;
struct server *srv = server_create(socket_path);
if (srv == NULL) { if (srv == NULL) {
fprintf(stderr, "server_create failed\n"); fprintf(stderr, "server_create failed\n");
return EXIT_FAILURE; return EXIT_FAILURE;
} }
printf("Listening on %s\n", socket_path);
while (1) { while (1) {
if (server_turn(srv) < 0) { if (server_turn(srv) < 0) {
fprintf(stderr, "server_turn failed\n"); fprintf(stderr, "server_turn failed\n");