Okay, well, I've narrowed down my question to spesific problem by removing questions related to inotify API.
I needed to be able to detect file changes, so I started learning the Linux inotify API. I searched for tutorials online and found one written by IBM (https://developer.ibm.com/tutorials/l-ubuntu-inotify). As I read the article and learned from it, the example code became very confusing.
From my understanding (These are not questions that I'm asking):
EVENT_SIZE: Is basically defines size of inotify_event struct which is 16 bytestruct inotify_event *event = ( struct inotify_event ∗ ) &buffer[ i ];: Here, a char pointer is cast as an inotify_event struct and later used as if like normal struct. How is that possible? Isn't this code prone to Undefined behaviours and Strict Aliasing problems?i += EVENT_SIZE + event‑>len: Why are we increasing the index byEVENT_SIZE + event->len? I really don't understand. Is it because when casting an element of a char array to a struct, the selected element behaves like a starting offset or something?
Okay I'm asking two related question :>, Is using char array safe to store struct data? If it is safe in the code below, how does this process work?
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/inotify.h>
#define EVENT_SIZE ( sizeof (struct inotify_event) )
#define BUF_LEN ( 1024 * ( EVENT_SIZE + 16 ) )
int main( int argc, char **argv )
{
int length, i = 0;
int fd;
int wd;
char buffer[BUF_LEN];
fd = inotify_init();
if ( fd < 0 ) {
perror( "inotify_init" );
}
wd = inotify_add_watch( fd, "/home/strike",
IN_MODIFY | IN_CREATE | IN_DELETE );
length = read( fd, buffer, BUF_LEN );
if ( length < 0 ) {
perror( "read" );
}
while ( i < length ) {
struct inotify_event *event = ( struct inotify_event * ) &buffer[ i ];
if ( event‑>len ) {
if ( event‑>mask & IN_CREATE ) {
if ( event‑>mask & IN_ISDIR ) {
printf( "The directory %s was created.\n", event‑>name );
}
else {
printf( "The file %s was created.\n", event‑>name );
}
}
else if ( event‑>mask & IN_DELETE ) {
if ( event‑>mask & IN_ISDIR ) {
printf( "The directory %s was deleted.\n", event‑>name );
}
else {
printf( "The file %s was deleted.\n", event‑>name );
}
}
else if ( event‑>mask & IN_MODIFY ) {
if ( event‑>mask & IN_ISDIR ) {
printf( "The directory %s was modified.\n", event‑>name );
}
else {
printf( "The file %s was modified.\n", event‑>name );
}
}
}
i += EVENT_SIZE + event‑>len;
}
( void ) inotify_rm_watch( fd, wd );
( void ) close( fd );
exit( 0 );
}
mallocmaybe written in a language other than C (putting it beyond what the C standard covers) or may be isolated in a separate…