Sunday, November 2, 2014

Unix Prog: Single Instance Daemon

1. Single Instance Daemon

Some daemons are implemented so that only one copy of the daemon should be running at a time for proper operation. That daemon might need exclusive access to a device or file.

The file and record locking mechanism provides the basic for one way to ensure that only one copy of daemon is running. If the daemon obtains a write-lock on an entire file, the lock will be removed automatically if the daemon exits.

2. File locking and single instance daemon
daemon.c:
 #include<stdio.h>  
 #include<stdlib.h>  
 #include<unistd.h>  
 #include<fcntl.h>  
 #include<syslog.h>  
 #include<errno.h>  
 #include<string.h>  
   
 #define LOCKFILE "daemon.txt"  
 #define LOCKMODE (S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH)  
   
 int lockfile(int fd)  
 {  
  struct flock fl;  
   
  fl.l_type = F_WRLCK;  
  fl.l_start = 0;  
  fl.l_whence = SEEK_SET;  
  fl.l_len = 0;  
  return(fcntl(fd, F_SETLK, &fl));  
 }  
   
 int already_running(void)  
 {  
  int fd;  
  char buf[16];  
   
  // Create the file  
  fd = open(LOCKFILE, O_RDWR|O_CREAT, LOCKMODE);  
  if(fd < 0) {  
   syslog(LOG_ERR, "open error!");  
   exit(1);  
  }  
   
  // Lock the file  
  if(lockfile(fd) < 0) {  
   if(errno == EACCES || errno == EAGAIN) {  
    close(fd);  
    return 1;  
   }  
   syslog(LOG_ERR, "can't lock %s", LOCKFILE);  
   exit(1);  
  }  
   
  ftruncate(fd, 0);  
   
  // Write to the file  
  sprintf(buf, "%ld", (long)getpid());  
  write(fd, buf, strlen(buf) + 1);  
  return 0;  
 }  
   
 int main(int argc, char* argv[])  
 {  
  if(already_running()) {  
   syslog(LOG_ERR, "daemon already running!");  
   exit(1);  
  }  
   
  exit(0);  
 }  

The program tries to lockfile to determine if the file is already locked by a previous running daemon.

No comments:

Post a Comment