How to Make a Daemon

In order to check sensors periodically with your board, you need to install and/or run some kind of program which runs in the background and calls itself periodically to do your bidding. Here is the basic structure of a daemon, written in C:

#include stdio.h    /*You need need brackets in real C.  Due to a technical*/
#include unistd.h   /*problem, I can't put them into this document!*/
#include stdlib.h
#include time.h
#include signal.h

void handle_sigs() 
{ /* handle_sigs */
  printf("Aaah! You're killing me!\n");
  sleep(5);
  printf("But it won't work! Ha ha ha ha ha ha!\n");
} /* handle_sigs */

int main() 
{ /* main */
  /* locals */

  /* daemonize */
  if (fork() != 0) 
    exit(0);
  signal(SIGHUP, handle_sigs);
  signal(SIGINT, handle_sigs);
  signal(SIGTERM, handle_sigs);
  signal(SIGQUIT, handle_sigs);

  srandom(time(NULL));

  while (1) {
    sleep(3600); /* sleep for one hour */
    /* execute your custom commands */
    /* for example, to run a shell command, use
    system( "mycommand > /mit/myusername/www/outputfile.html");
    */
 } /* while */
  exit(0);
} /* main */
The above code example will run the command my command every hour from the time of execution and cat the output to a file called outputfile.html. Make sure your shell allows you to clobber existing files with a file redireciton! If your shell does not allow you to do this, you can get around it by inserting "rm filename; mycommand > filename" in place of the sample string. This example suggests a cheesy way of updating a web page by writing to a file in a www directory which is pointed to by some link on say, your home page. Note that you can append to a file as well as overwriting it using file redirection. Appending is done by

mycommand >> filename.

In order to run your daemon, just type the command name and the program will automatically "install" itself and exit. In order to kill the daemon, just run ps, identify the process in the table, and kill -9 .

Another way to execute commands periodically is to use crond, but I don't know how to use it.


Andrew Huang <bunnie@mit.edu>
Ara Knaian <ara@mit.edu>