char buf[BUF_LEN]_attribute_((aligned(4)));
ssize_t len, i = 0;
/* read BUF_LEN bytes' worth of events */
len = read (fd, buf, BUF_LEN);
/* loop over every read event until none remain */
while (i < len) {
struct inotify_event *event =
(struct inotify_event *) &buf[i];
Monitoring File Events | 239
printf ("wd=%d mask=%d cookie=%d len=%d dir=%s\n",
event->wd, event->mask,
event->cookie, event->len,
(event->mask & IN_ISDIR) ? "yes" : "no");
/* if there is a name, print it */
if (event->len)
printf ("name=%s\n", event->name);
/* update the index to the start of the next event */
i += sizeof (struct inotify_event) + event->len;
}

- 645
- 2
- 8
- 16
3 Answers
char buf[BUF_LEN]_attribute_((aligned(4)));
It specifies a minimum alignment for the variable buf
, measured in bytes.
It causes the compiler to allocate the variable buf
on a 4-byte boundary.
This should be a good read.

- 202,538
- 53
- 430
- 533
-
It's also a really ugly nonportable way to write this. The portable way would be to use a union with the larger type you want to ensure alignment compatibility with. – R.. GitHub STOP HELPING ICE Aug 14 '11 at 18:32
-
Or better yet, just use an array of `inotify_event` structures. There's no need for a `char` buffer whatsoever! – R.. GitHub STOP HELPING ICE Aug 14 '11 at 18:33
-
I tried to read the linked article and I still don't understand what ((aligned(x))) does. What is a "boundary" in the context of memory? How does it look? Where are the examples? – user2762996 Dec 28 '21 at 15:08
The instruction tells the compiler to put the buffer on an address that's a multiple of four bytes.
On some processors, this has no effect, on other processors it speeds up the memory access if you don't read a single byte at a time but rather 2, 4 or 8 (16, 32 and 64 bit) and on some processors it is even required for 2, 4 or 8 byte access (otherwise a bus error occurrs).
In this case, this is indeed relevant since the buffer is later access as series of inotify_event
structs, which contain members that are accessed as 16, 32 or 64 bit values.

- 75,595
- 17
- 168
- 206
This aligns the memory allocated to buf on a 4-byte boundary. This can speed memory transfers between the CPU and main memory among other things.

- 3,566
- 1
- 18
- 36