lock.c 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. #include <stdlib.h>
  2. #include <stdio.h>
  3. #include <fcntl.h>
  4. #include <unistd.h>
  5. #include <sys/types.h>
  6. #include <sys/stat.h>
  7. #include <signal.h>
  8. #include "local_proto.h"
  9. #include <grass/gis.h>
  10. /******************************************************************
  11. *lock file pid
  12. *
  13. * this programs "locks" the file for process pid:
  14. *
  15. * 1. if file exists, the pid is read out of the file. if this
  16. * process is still running, the file is considered locked.
  17. * exit(1)
  18. * 2. if file does not exist, or if file exists but process is not
  19. * running (ie, lock was not removed), the file is locked for
  20. * process pid by writing pid into the file.
  21. * exit(0).
  22. ******************************************************************/
  23. #include <errno.h>
  24. extern int errno;
  25. int main(int argc, char *argv[])
  26. {
  27. int pid;
  28. int lockpid;
  29. int lock;
  30. int locked;
  31. if (argc != 3 || sscanf(argv[2], "%d", &lockpid) != 1)
  32. G_fatal_error("usage: %s file pid", argv[0]);
  33. #define file argv[1]
  34. #ifdef __MINGW32__
  35. G_warning("Attention!");
  36. G_warning("Locking is not supported on Windows!");
  37. exit(0);
  38. #else
  39. locked = 0;
  40. if ((lock = open(file, 0)) >= 0) { /* file exists */
  41. G_sleep(1); /* allow time for file creator to write its pid */
  42. if (read(lock, &pid, sizeof pid) == sizeof pid)
  43. locked = find_process(pid);
  44. close(lock);
  45. }
  46. if (locked)
  47. exit(1);
  48. if ((lock = creat(file, 0666)) < 0) {
  49. perror(file);
  50. G_fatal_error("%s: ", argv[0]);
  51. }
  52. if (write(lock, &lockpid, sizeof lockpid) != sizeof lockpid)
  53. G_fatal_error("%s: can't write lockfile %s (disk full? Permissions?)",
  54. argv[0], file);
  55. close(lock);
  56. exit(0);
  57. #endif
  58. }
  59. int find_process(int pid)
  60. {
  61. /* attempt to kill pid with NULL signal. if success, then
  62. process pid is still running. otherwise, must check if
  63. kill failed because no such process, or because user is
  64. not owner of process
  65. */
  66. #ifdef __MINGW32__
  67. return 0;
  68. #else
  69. if (kill(pid, 0) == 0)
  70. return 1;
  71. return errno != ESRCH;
  72. #endif
  73. }