]> git.lizzy.rs Git - bspwm.git/blob - bspc.c
New setting: `auto_alternate`
[bspwm.git] / bspc.c
1 #include <stdlib.h>
2 #include <string.h>
3 #include <sys/socket.h>
4 #include <sys/un.h>
5 #include <unistd.h>
6 #include "helpers.h"
7 #include "common.h"
8
9 int main(int argc, char *argv[])
10 {
11     int sock_fd;
12     struct sockaddr_un sock_address;
13     size_t msglen = 0;
14     char msg[BUFSIZ];
15     char rsp[BUFSIZ];
16
17     if (argc < 2)
18         err("No arguments given.\n");
19
20     char *sock_path = getenv(SOCKET_ENV_VAR);
21     if (sock_path == NULL || strlen(sock_path) == 0)
22         warn("The environment variable '%s' is not set or empty, we will use: '%s'.\n", SOCKET_ENV_VAR, DEFAULT_SOCKET_PATH);
23     else if (sizeof(sock_address.sun_path) <= strlen(sock_path))
24         err("The string can't fit in the socket address: '%s'.\n", sock_path);
25
26     sock_address.sun_family = AF_UNIX;
27     strncpy(sock_address.sun_path, (sock_path == NULL ? DEFAULT_SOCKET_PATH : sock_path), sizeof(sock_address.sun_path));
28     sock_address.sun_path[sizeof(sock_address.sun_path) - 1] = 0;
29
30     for (int offset = 0, len = sizeof(msg), n = 0; --argc && ++argv && len > 0; offset += n, len -= n)
31         n = snprintf(msg + offset, len, "%s ", *argv);
32
33     msglen = strlen(msg);
34     if (msg[msglen - 1] == ' ')
35         msg[--msglen] = '\0';
36
37     sock_fd = socket(AF_UNIX, SOCK_STREAM, 0);
38     if (sock_fd == -1)
39         err("Failed to create the socket.\n");
40
41     if (connect(sock_fd, (struct sockaddr *) &sock_address, sizeof(sock_address)) == -1)
42         err("Failed to connect to the socket.\n");
43
44     if (send(sock_fd, msg, msglen, 0) == -1)
45         err("Failed to send the data.\n");
46
47     int n = recv(sock_fd, rsp, sizeof(rsp), 0);
48     if (n == -1) {
49         err("Failed to get the response.\n");
50     } else if (n > 0) {
51         rsp[n] = '\0';
52         printf("%s\n", rsp);
53     }
54
55     if (sock_fd)
56         close(sock_fd);
57
58     return EXIT_SUCCESS;
59 }