0

I am building an application which has to check a directory for new files then, for each new file, launch a new process which manipulate that file (after which the file gets deleted).

Basically the program reduces to the following:

while(1) {
    DIR * directory = opendir("/example"); 
    struct dirent * directory_data;
    if(directory) {
       while((directory_data = readdir(directory)) != NULL) {
          if(directory_data->d_type == DT_REG) {
              // Checking if that file is new and was not already manipulated, by a previous loop (stored the last loop list of files in a char array)
              execute_manipulator(directory_data->d_name);
           }
        }
    }
    // With some error checking
    closedir(directory);
    usleep(300000); // 0.3 secs
}

The question is regarding speed. Is there a faster way to check a directory for new files than using dirent's opendir and readdir? I noted out that once at 3-4 seconds the CPU usage of program is around 1% (I would like to make it faster, almost not to be noticed, if possible).

Note: I also used to store previous loop list of files in a char array rather than storing the last higher mtime and using stat, to check if the file is new, because using RAM should be much faster.

Thank you!

  • UNIX? Do you mean Mac OSX? Because that's the only commonly encountered UNIX. The problem with UNIX is that is a lowest common denominator. – MSalters Apr 18 '19 at 07:08
  • 2
    What OS? Linux has `inotify` and the various BSDs have `kqueue` which would be handy. – Shawn Apr 18 '19 at 07:09
  • I never did something like that on linux, but can't you register some sort of hook to get notified when a file was created and then react on that event? – Trickzter Apr 18 '19 at 07:11
  • @Shawn I updated the tag and specified `CentOS 7` as Operating System. Thank you! – NETCreator Hosting - WebDesign Apr 18 '19 at 07:12
  • 2
    The use [`libinotify`](http://man7.org/linux/man-pages/man7/inotify.7.html) – KamilCuk Apr 18 '19 at 07:16
  • Possible duplicate of [How to continuously monitor the directory using dnotify /inotify command](https://stackoverflow.com/questions/7566569/how-to-continuously-monitor-the-directory-using-dnotify-inotify-command) – Mathieu Apr 18 '19 at 07:19

0 Answers0