GRASS 8 Programmer's Manual 8.6.0dev(2026)-ddeab64dbf
Loading...
Searching...
No Matches
lock.c
Go to the documentation of this file.
1#include <stdlib.h>
2#include <stdio.h>
3#include <string.h>
4#include <fcntl.h>
5#include <unistd.h>
6#include <sys/types.h>
7#include <sys/stat.h>
8#include <signal.h>
9#include "local_proto.h"
10#include <grass/gis.h>
11#include <grass/glocale.h>
12
13/******************************************************************
14 *lock file pid
15 *
16 * this programs "locks" the file for process pid:
17 *
18 * 1. if file exists, the pid is read out of the file. if this
19 * process is still running, the file is considered locked.
20 * exit(2).
21 * 2. something weird happened. G_fatal_error() aka exit(1)
22 * 3. if file does not exist, or if file exists but process is not
23 * running (ie, lock was not removed), the file is locked for
24 * process pid by writing pid into the file.
25 * exit(0).
26 ******************************************************************/
27
28#include <errno.h>
29
30int main(int argc, char *argv[])
31{
32 int pid;
33 int lockpid;
34 int lock;
35 int locked;
36
37 if (argc != 3 || sscanf(argv[2], "%d", &lockpid) != 1)
38 G_fatal_error(_("Usage: %s file pid"), argv[0]);
39#define file argv[1]
40
41#ifdef _WIN32
42 G_warning(_("Concurrent mapset locking is not supported on Windows"));
43 exit(0);
44#else
45 locked = 0;
46 if ((lock = open(file, 0)) >= 0) { /* file exists */
47 G_sleep(1); /* allow time for file creator to write its pid */
48 if (read(lock, &pid, sizeof pid) == sizeof pid)
49 locked = find_process(pid);
50 close(lock);
51 }
52 if (locked)
53 exit(2);
54
55 if ((lock = creat(file, 0666)) < 0) {
56 perror(file);
57 G_fatal_error("%s: ", argv[0]);
58 }
59 if (write(lock, &lockpid, sizeof lockpid) != sizeof lockpid)
60 G_fatal_error(_("Unable to write lockfile %s (%s)"), file,
62 close(lock);
63 exit(0);
64#endif
65}
66
67int find_process(int pid)
68{
69 /* attempt to kill pid with NULL signal. if success, then
70 process pid is still running. otherwise, must check if
71 kill failed because no such process, or because user is
72 not owner of process
73 */
74#ifdef _WIN32
75 return 0;
76#else
77 if (kill(pid, 0) == 0)
78 return 1;
79 return errno != ESRCH;
80#endif
81}
void void void void G_fatal_error(const char *,...) __attribute__((format(printf
void G_warning(const char *,...) __attribute__((format(printf
void G_sleep(unsigned int)
Definition sleep.c:11
Header file for msvc/fcntl.c.
#define creat
Definition fcntl.h:34
#define open
Definition fcntl.h:33
#define _(str)
Definition glocale.h:10
int find_process(int pid)
Definition lock.c:67
#define file
#define read
Definition unistd.h:5
#define close
Definition unistd.h:8
#define write
Definition unistd.h:6
int main(void)
Definition winlocale.c:201