]> git.lizzy.rs Git - bspwm.git/blob - bspc.c
Implement ICCCM's WM_TAKE_FOCUS behavior
[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     char msg[BUFSIZ];
14     char rsp[BUFSIZ];
15
16     if (argc < 2)
17         err("No arguments given.\n");
18
19     char *sock_path = getenv(SOCKET_ENV_VAR);
20     if (sock_path != NULL && sizeof(sock_address.sun_path) <= strlen(sock_path))
21         err("The socket path can't fit into the socket address.\n");
22
23     sock_address.sun_family = AF_UNIX;
24     strncpy(sock_address.sun_path, (sock_path == NULL ? DEFAULT_SOCKET_PATH : sock_path), sizeof(sock_address.sun_path));
25     sock_address.sun_path[sizeof(sock_address.sun_path) - 1] = 0;
26
27     argc--, argv++;
28     int msg_len = 0;
29
30     for (int offset = 0, rem = sizeof(msg), n = 0; argc > 0 && rem > 0; offset += n, rem -= n, argc--, argv++) {
31         n = snprintf(msg + offset, rem, "%s%c", *argv, 0);
32         msg_len += n;
33     }
34
35     if ((sock_fd = socket(AF_UNIX, SOCK_STREAM, 0)) == -1)
36         err("Failed to create the socket.\n");
37
38     if (connect(sock_fd, (struct sockaddr *) &sock_address, sizeof(sock_address)) == -1)
39         err("Failed to connect to the socket.\n");
40
41     if (send(sock_fd, msg, msg_len, 0) == -1)
42         err("Failed to send the data.\n");
43
44     int ret = EXIT_SUCCESS;
45
46     int n = recv(sock_fd, rsp, sizeof(rsp), 0);
47     if (n == -1) {
48         err("Failed to get the response.\n");
49     } else if (n > 0) {
50         if (n == 1 && rsp[0] == MESSAGE_FAILURE) {
51             ret = EXIT_FAILURE;
52         } else {
53             rsp[n] = '\0';
54             printf("%s\n", rsp);
55         }
56     }
57
58     if (sock_fd)
59         close(sock_fd);
60
61     return ret;
62 }