lock.c 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  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. {
  42. G_sleep(1); /* allow time for file creator to write its pid */
  43. if (read (lock, &pid, sizeof pid) == sizeof pid)
  44. locked = find_process (pid);
  45. close (lock);
  46. }
  47. if (locked)
  48. exit(1);
  49. if ((lock = creat (file, 0666)) < 0)
  50. {
  51. perror (file);
  52. G_fatal_error("%s: ", argv[0]);
  53. }
  54. if (write(lock, &lockpid, sizeof lockpid) != sizeof lockpid)
  55. G_fatal_error("%s: can't write lockfile %s (disk full? Permissions?)", argv[0], file);
  56. close (lock);
  57. exit(0);
  58. #endif
  59. }
  60. int
  61. find_process (int pid)
  62. {
  63. /* attempt to kill pid with NULL signal. if success, then
  64. process pid is still running. otherwise, must check if
  65. kill failed because no such process, or because user is
  66. not owner of process
  67. */
  68. #ifdef __MINGW32__
  69. return 0;
  70. #else
  71. if (kill (pid, 0) == 0)
  72. return 1;
  73. return errno != ESRCH;
  74. #endif
  75. }