views:

170

answers:

3

I am implementing an SMTP-sender in C which is supposed to read a file from a directory whenever it is created, process data and delete the file.

How can I implement this polling function which should keep doing this automatically?

+4  A: 

Look into inotify and see if it will suffice for your needs. inotify allows you to use a single file descriptor to monitor events in your target directory. You can avoid polling by using select() and be immediately notified of any files created in the directory so that you can do your processing.

This article has some example code. I am sure there are other examples spread about the web.

Duck
+5  A: 

A simple option is to run your program periodically from cron. The program can use the Linux API call readdir to iterate through a directory. It doesn't have to actively monitor the directory.

Here's a simple code example:

#include <stdio.h>
#include <sys/types.h>
#include <dirent.h>
int main()
{
   DIR* dp = opendir(".");
   struct dirent* de;
   while (de = readdir(dp))
   { 
     if (de->d_type != DT_REG) // Only print regular files
        continue;
      printf("Found file %s\n", de->d_name);
   }
   closedir(dp);
}

Disclaimer: For the sake of simplicity I did not include code to check or handle error conditons.

Andomar
A: 

By what I get from your question its a good case for interprocess communication.

You say that you need to be notified when a file in a directory is created. Now, doing interprocess communication through files is bad in my opinion.

In Unix you have several alternatives for interprocess communication as this guide details. Using Unix sockets would be the simplest way to go.

If you have written the other process that now creates a file for interprocess communication you could change the implementation to write it to the socket.

ardsrk
I know about IPC but it is not what I require here.
Alex Xander