Detect when a new file was created

1

Details: I have an application where:

  • I have an AJAX request with JQuery triggered every time I new users are inserted by passing the necessary data to a PHP file that receives them via POST and creates a JSON file with these data.

  • The data from the JSON file will be interpreted with C language using libjson for later storing in the database sqlite.

  • Question: How to make the C language "wait" and create a warning when this new file is generated so that another C function can catch it automatically and play in the second process?

        
    asked by anonymous 17.11.2015 / 15:58

    2 answers

    3

    I'll assume you're dealing with linux environment. Here is a very interesting implementation for this problem: File Events Notification

    Basically a thread is created to monitor a directory while a process is running, keeping it alive. Note that% w /% can "hear" several different states. These being:

    • FILE_ACCESS: File / Directory monitored has been accessed
    • FILE_MODIFIED: File / Directory monitored has been modified
    • FILE_ATTRIB: File / Monitored directory had an altered attribute
    • FILE_NOFOLLOW: Do not follow symlinks
    • FILE_DELETE: File / Directory has been deleted
    • FILE_RENAME_TO: File / directory renamed
    • FILE_RENAME_FROM: File / directory renamed
    • UNMOUNTED: File / Directory has been unmounted
    • MOUNTEDOVER: File / directory was mounted

    I believe these events have resolved your case. In the code the treatment for each event was via thread and if , but I suggest you create a else to facilitate maintenance.

        
    17.11.2015 / 17:12
    2

    If it's in linux : In these situations I usually use the inotify library. There is inotify interface for various programming languages. (see man inotify for information on interface C).

    Below is an example in Perl that waits for someone to create a file in the "Dir" folder and invokes a command (for example, the program you create in the database) when this happens.

    #!/usr/bin/perl
    
     use Linux::Inotify2;
    
     my $inotify = new Linux::Inotify2 or die "unable to inotify: $!";
    
     $inotify->watch ("Dir", IN_CREATE, # ... IN_MODIFY,
        sub { my $e = shift;
              my $name = $e->fullname;
              system("ls -la '$name'");             ##  ==> chamar o teu programa C
              print "$name was created\n" if $e->IN_CREATE; }
        );
    
     1 while $inotify->poll;
    
        
    17.11.2015 / 17:13