Automatically remove snark.lock file on application exit using atexit() registration
authorKevin M. Rosenberg <kevin@rosenberg.net>
Mon, 12 Feb 2018 19:53:49 +0000 (12:53 -0700)
committerKevin M. Rosenberg <kevin@rosenberg.net>
Mon, 12 Feb 2018 19:53:49 +0000 (12:53 -0700)
src/snark/snark.cpp

index 08e1fecdfef13402153f869d35be6ac5c4de0e72..07b8521043e397625bfdbd360272fd31ae0619e0 100644 (file)
@@ -220,6 +220,9 @@ static const INTEGER main_codes[NUMBER_OF_COMMANDS] =
   CHAR2INT('s','u','p','e')
 };
 
+static const char* kLockFilename = "snark.lock";
+static int gLockFd = -1;
+
 int FindKeywordCode(int word)
 {
   for(int i = 0; i < NUMBER_OF_COMMANDS; i++) {       // find keyword code
@@ -260,6 +263,16 @@ INTEGER GetCommandPhase(INTEGER code)
   return Phase[code];
 }
 
+void unlinkLockfile(void) {
+#ifndef __CYGWIN__
+  if (gLockFd >= 0) {
+    close(gLockFd);
+    if (unlink(kLockFilename) != 0) {
+      fprintf(stderr, "Error unlinking lock file\n");
+    }
+  }
+#endif
+}
 
 int snark(int argc, char *argv[])
 {
@@ -285,19 +298,22 @@ int snark(int argc, char *argv[])
   // bug 179 - swr - 10/30/05
 #ifndef __CYGWIN__
   // bug 167 - swr - 9/24/05
-  int lfp=open("snark.lock",O_RDWR|O_CREAT,0640);
-  if (lfp<0) {
+  gLockFd = open(kLockFilename,O_RDWR|O_CREAT,0640);
+  if (gLockFd < 0) {
     fprintf(stderr, "can't create lock file in current directory - check directory permissions\n");
     exit(1); /* can not open */
   }
-  if (lockf(lfp,F_TLOCK,0)<0) {
+  if (lockf(gLockFd,F_TLOCK,0)<0) {
     fprintf(stderr, "multiple snark executions in the same directory are not allowed!\n");
     exit(0); /* can not lock */
   }
   /* only first instance continues */
   char str[10];
   sprintf(str,"%d\n",getpid());
-  write(lfp,str,strlen(str)); /* record pid to lockfile */
+  write(gLockFd,str,strlen(str)); /* record pid to lockfile */
+
+  atexit(unlinkLockfile);
+  
 #endif
 
   // bug 187 - allow input filename on command line - swr - 11/11/05
@@ -490,6 +506,7 @@ int snark(int argc, char *argv[])
   };
 
   fprintf(output, "\n");
+  
   return 0;
 }