4 * i3 - an improved dynamic tiling window manager
6 * © 2009 Michael Stapelberg and contributors
8 * See file LICENSE for license information.
10 * i3-msg/main.c: Utility which sends messages to a running i3-instance using
11 * IPC via UNIX domain sockets.
13 * This serves as an example for how to send your own messages to i3.
14 * Additionally, it’s even useful sometimes :-).
19 #include <sys/types.h>
20 #include <sys/socket.h>
31 * Formats a message (payload) of the given size and type and sends it to i3 via
32 * the given socket file descriptor.
35 static void ipc_send_message(int sockfd, uint32_t message_size,
36 uint32_t message_type, uint8_t *payload) {
37 int buffer_size = strlen("i3-ipc") + sizeof(uint32_t) + sizeof(uint32_t) + message_size;
38 char msg[buffer_size];
41 strcpy(walk, "i3-ipc");
42 walk += strlen("i3-ipc");
43 memcpy(walk, &message_size, sizeof(uint32_t));
44 walk += sizeof(uint32_t);
45 memcpy(walk, &message_type, sizeof(uint32_t));
46 walk += sizeof(uint32_t);
47 memcpy(walk, payload, message_size);
50 int bytes_to_go = buffer_size;
51 while (sent_bytes < bytes_to_go) {
52 int n = write(sockfd, msg + sent_bytes, bytes_to_go);
54 err(EXIT_FAILURE, "write() failed");
61 int main(int argc, char *argv[]) {
62 char *socket_path = "/tmp/i3-ipc.sock";
63 int o, option_index = 0;
65 static struct option long_options[] = {
66 {"socket", required_argument, 0, 's'},
67 {"type", required_argument, 0, 't'},
68 {"version", no_argument, 0, 'v'},
69 {"help", no_argument, 0, 'h'},
73 char *options_string = "s:t:vh";
75 while ((o = getopt_long(argc, argv, options_string, long_options, &option_index)) != -1) {
77 socket_path = strdup(optarg);
79 } else if (o == 't') {
80 printf("currently only commands are implemented\n");
81 } else if (o == 'v') {
82 printf("i3-msg " I3_VERSION);
84 } else if (o == 'h') {
85 printf("i3-msg " I3_VERSION);
86 printf("i3-msg [-s <socket>] [-t <type>] <message>\n");
92 fprintf(stderr, "Error: missing message\n");
93 fprintf(stderr, "i3-msg [-s <socket>] [-t <type>] <message>\n");
97 int sockfd = socket(AF_LOCAL, SOCK_STREAM, 0);
99 err(EXIT_FAILURE, "Could not create socket");
101 struct sockaddr_un addr;
102 memset(&addr, 0, sizeof(struct sockaddr_un));
103 addr.sun_family = AF_LOCAL;
104 strcpy(addr.sun_path, socket_path);
105 if (connect(sockfd, (const struct sockaddr*)&addr, sizeof(struct sockaddr_un)) < 0)
106 err(EXIT_FAILURE, "Could not connect to i3");
108 ipc_send_message(sockfd, strlen(argv[optind]), 0, (uint8_t*)argv[optind]);