X-Git-Url: https://git.lizzy.rs/?a=blobdiff_plain;f=bspc.c;h=c5e1697e689528ea9aaa843fe84810aadd4be03b;hb=e28581baf3656eef20b47e8c4ea8054215935f38;hp=8ab75320e81a19076d0facc19118b93b2dce27b8;hpb=7aa12b0cd61e1698b5e9d39120a2effa9a14c51f;p=bspwm.git diff --git a/bspc.c b/bspc.c index 8ab7532..c5e1697 100644 --- a/bspc.c +++ b/bspc.c @@ -1,40 +1,62 @@ -#include #include #include #include #include #include - -#define SOCK_PATH "BSPWM_SOCKET" +#include "helpers.h" +#include "common.h" int main(int argc, char *argv[]) { - int sock_fd, i; + int sock_fd; struct sockaddr_un sock_address; - char *sock_path; - char response[BUFSIZ]; - int num_args = argc - 1; - char **args = (argv + 1); - - if (num_args < 1) - return; + char msg[BUFSIZ]; + char rsp[BUFSIZ]; - sock_path = getenv(SOCK_PATH); + if (argc < 2) + err("No arguments given.\n"); - if (sock_path == NULL) - return; + char *sock_path = getenv(SOCKET_ENV_VAR); + if (sock_path != NULL && sizeof(sock_address.sun_path) <= strlen(sock_path)) + err("The socket path can't fit into the socket address.\n"); sock_address.sun_family = AF_UNIX; - strcpy(sock_address.sun_path, sock_path); + strncpy(sock_address.sun_path, (sock_path == NULL ? DEFAULT_SOCKET_PATH : sock_path), sizeof(sock_address.sun_path)); + sock_address.sun_path[sizeof(sock_address.sun_path) - 1] = 0; + + argc--, argv++; + int msg_len = 0; + + for (int offset = 0, rem = sizeof(msg), n = 0; argc > 0 && rem > 0; offset += n, msg_len = offset, rem -= n, argc--, argv++) { + n = snprintf(msg + offset, rem, "%s%c", *argv, 0); + msg_len += n; + } - sock_fd = socket(AF_UNIX, SOCK_STREAM, 0); - connect(sock_fd, (struct sockaddr *) &sock_address, sizeof(sock_address)); + if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1) + err("Failed to create the socket.\n"); - for (i = 0; i < num_args; i++) { - send(sock_fd, args[i], strlen(args[i]), 0); - - if (recv(sock_fd, response, sizeof(response), 0) > 0) - printf("%s\n", response); + if (connect(sock_fd, (struct sockaddr *) &sock_address, sizeof(sock_address)) == -1) + err("Failed to connect to the socket.\n"); + + if (send(sock_fd, msg, msg_len, 0) == -1) + err("Failed to send the data.\n"); + + int ret = EXIT_SUCCESS; + + int n = recv(sock_fd, rsp, sizeof(rsp), 0); + if (n == -1) { + err("Failed to get the response.\n"); + } else if (n > 0) { + if (n == 1 && rsp[0] == MESSAGE_FAILURE) { + ret = EXIT_FAILURE; + } else { + rsp[n] = '\0'; + printf("%s\n", rsp); + } } - + + if (sock_fd) + close(sock_fd); + + return ret; }