1 /** 2 * @file op_lockfile.c 3 * PID-based lockfile management 4 * 5 * @remark Copyright 2002 OProfile authors 6 * @remark Read the file COPYING 7 * 8 * @author John Levon 9 * @author Philippe Elie 10 */ 11 12 #include "op_lockfile.h" 13 #include "op_file.h" 14 15 #include <errno.h> 16 17 #include <sys/types.h> 18 #include <stdio.h> 19 #include <signal.h> 20 #include <unistd.h> 21 22 static pid_t op_read_lock_file(char const * file) 23 { 24 FILE * fp; 25 pid_t value; 26 27 fp = fopen(file, "r"); 28 if (fp == NULL) 29 return 0; 30 31 if (fscanf(fp, "%d", &value) != 1) { 32 fclose(fp); 33 return 0; 34 } 35 36 fclose(fp); 37 38 return value; 39 } 40 41 42 int op_write_lock_file(char const * file) 43 { 44 FILE * fp; 45 46 if (op_file_readable(file)) { 47 pid_t pid = op_read_lock_file(file); 48 49 /* FIXME: ESRCH vs. EPERM */ 50 if (kill(pid, 0)) { 51 int err = unlink(file); 52 fprintf(stderr, "Removing stale lock file %s\n", 53 file); 54 if (err) 55 return err; 56 } else { 57 return EEXIST; 58 } 59 } 60 61 fp = fopen(file, "w"); 62 if (!fp) 63 return errno; 64 65 fprintf(fp, "%d", getpid()); 66 fclose(fp); 67 68 return 0; 69 } 70