]> git.sur5r.net Git - i3/i3/blob - libi3/ipc_send_message.c
28cb8359207e128b648a664824b6dcc59950e07e
[i3/i3] / libi3 / ipc_send_message.c
1 /*
2  * vim:ts=4:sw=4:expandtab
3  *
4  * i3 - an improved dynamic tiling window manager
5  * © 2009-2013 Michael Stapelberg and contributors (see also: LICENSE)
6  *
7  */
8 #include <string.h>
9 #include <stdlib.h>
10 #include <unistd.h>
11 #include <stdint.h>
12 #include <err.h>
13 #include <errno.h>
14
15 #include <i3/ipc.h>
16
17 #include "libi3.h"
18
19 /*
20  * Formats a message (payload) of the given size and type and sends it to i3 via
21  * the given socket file descriptor.
22  *
23  * Returns -1 when write() fails, errno will remain.
24  * Returns 0 on success.
25  *
26  */
27 int ipc_send_message(int sockfd, const uint32_t message_size,
28                      const uint32_t message_type, const uint8_t *payload) {
29     const i3_ipc_header_t header = {
30         /* We don’t use I3_IPC_MAGIC because it’s a 0-terminated C string. */
31         .magic = {'i', '3', '-', 'i', 'p', 'c'},
32         .size = message_size,
33         .type = message_type};
34
35     size_t sent_bytes = 0;
36     int n = 0;
37
38     /* This first loop is basically unnecessary. No operating system has
39      * buffers which cannot fit 14 bytes into them, so the write() will only be
40      * called once. */
41     while (sent_bytes < sizeof(i3_ipc_header_t)) {
42         if ((n = write(sockfd, ((void *)&header) + sent_bytes, sizeof(i3_ipc_header_t) - sent_bytes)) == -1) {
43             if (errno == EAGAIN)
44                 continue;
45             return -1;
46         }
47
48         sent_bytes += n;
49     }
50
51     sent_bytes = 0;
52
53     while (sent_bytes < message_size) {
54         if ((n = write(sockfd, payload + sent_bytes, message_size - sent_bytes)) == -1) {
55             if (errno == EAGAIN)
56                 continue;
57             return -1;
58         }
59
60         sent_bytes += n;
61     }
62
63     return 0;
64 }