op_lockfile.c

Go to the documentation of this file.
00001 
00012 #include "op_lockfile.h"
00013 #include "op_file.h"
00014 
00015 #include <errno.h>
00016 
00017 #include <sys/types.h>
00018 #include <stdio.h>
00019 #include <signal.h>
00020 #include <unistd.h>
00021 
00022 static pid_t op_read_lock_file(char const * file)
00023 {
00024     FILE * fp;
00025     pid_t value;
00026 
00027     fp = fopen(file, "r");
00028     if (fp == NULL)
00029         return 0;
00030 
00031     if (fscanf(fp, "%d", &value) != 1) {
00032         fclose(fp);
00033         return 0;
00034     }
00035 
00036     fclose(fp);
00037 
00038     return value;
00039 }
00040 
00041 
00042 int op_write_lock_file(char const * file)
00043 {
00044     FILE * fp;
00045 
00046     if (op_file_readable(file)) {
00047         pid_t pid = op_read_lock_file(file);
00048 
00049         /* FIXME: ESRCH vs. EPERM */
00050         if (kill(pid, 0)) {
00051             int err = unlink(file);
00052             fprintf(stderr, "Removing stale lock file %s\n",
00053                 file);
00054             if (err)
00055                 return err;
00056         } else {
00057             return EEXIST;
00058         }
00059     }
00060 
00061     fp = fopen(file, "w");
00062     if (!fp)
00063         return errno;
00064 
00065     fprintf(fp, "%d", getpid());
00066     fclose(fp);
00067 
00068     return 0;
00069 }

Generated on 8 Nov 2012 for Oprofile by  doxygen 1.6.1