]> git.sur5r.net Git - i3/i3/blob - libi3/ipc_connect.c
Merge pull request #3435 from vivien/i3-msg/subscribe
[i3/i3] / libi3 / ipc_connect.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include "libi3.h"
9
10 #include <sys/types.h>
11 #include <sys/socket.h>
12 #include <sys/un.h>
13 #include <string.h>
14 #include <err.h>
15 #include <stdlib.h>
16 #include <unistd.h>
17 #include <fcntl.h>
18
19 /*
20  * Connects to the i3 IPC socket and returns the file descriptor for the
21  * socket. die()s if anything goes wrong.
22  *
23  */
24 int ipc_connect(const char *socket_path) {
25     char *path = NULL;
26     if (socket_path != NULL) {
27         path = sstrdup(socket_path);
28     }
29
30     if (path == NULL) {
31         if ((path = getenv("I3SOCK")) != NULL) {
32             path = sstrdup(path);
33         }
34     }
35
36     if (path == NULL) {
37         path = root_atom_contents("I3_SOCKET_PATH", NULL, 0);
38     }
39
40     if (path == NULL) {
41         path = sstrdup("/tmp/i3-ipc.sock");
42     }
43
44     int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
45     if (sockfd == -1)
46         err(EXIT_FAILURE, "Could not create socket");
47
48     (void)fcntl(sockfd, F_SETFD, FD_CLOEXEC);
49
50     struct sockaddr_un addr;
51     memset(&addr, 0, sizeof(struct sockaddr_un));
52     addr.sun_family = AF_LOCAL;
53     strncpy(addr.sun_path, path, sizeof(addr.sun_path) - 1);
54     if (connect(sockfd, (const struct sockaddr *)&addr, sizeof(struct sockaddr_un)) < 0)
55         err(EXIT_FAILURE, "Could not connect to i3 on socket %s", path);
56     free(path);
57     return sockfd;
58 }