Merge with gitk-show-ref
[git/mingw.git] / lockfile.c
blobbf80246dc3f6867ba1f57a422a272e6e9f7dac20
1 /*
2 * Copyright (c) 2005, Junio C Hamano
3 */
4 #include "cache.h"
6 static struct lock_file *lock_file_list;
8 static void remove_lock_file(void)
10 while (lock_file_list) {
11 if (lock_file_list->filename[0]) {
12 close(lock_file_list->fd);
13 unlink(lock_file_list->filename);
15 lock_file_list = lock_file_list->next;
19 static void remove_lock_file_on_signal(int signo)
21 remove_lock_file();
22 signal(SIGINT, SIG_DFL);
23 raise(signo);
26 static int lock_file(struct lock_file *lk, const char *path)
28 sprintf(lk->filename, "%s.lock", path);
29 lk->fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
30 if (0 <= lk->fd) {
31 if (!lk->on_list) {
32 lk->next = lock_file_list;
33 lock_file_list = lk;
34 lk->on_list = 1;
36 if (lock_file_list) {
37 signal(SIGINT, remove_lock_file_on_signal);
38 atexit(remove_lock_file);
40 if (adjust_shared_perm(lk->filename))
41 return error("cannot fix permission bits on %s",
42 lk->filename);
44 else
45 lk->filename[0] = 0;
46 return lk->fd;
49 int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on_error)
51 int fd = lock_file(lk, path);
52 if (fd < 0 && die_on_error)
53 die("unable to create '%s.lock': %s", path, strerror(errno));
54 return fd;
57 int commit_lock_file(struct lock_file *lk)
59 char result_file[PATH_MAX];
60 int i;
61 close(lk->fd);
62 strcpy(result_file, lk->filename);
63 i = strlen(result_file) - 5; /* .lock */
64 result_file[i] = 0;
65 unlink(result_file);
66 i = rename(lk->filename, result_file);
67 lk->filename[0] = 0;
68 return i;
71 void rollback_lock_file(struct lock_file *lk)
73 if (lk->filename[0]) {
74 close(lk->fd);
75 unlink(lk->filename);
77 lk->filename[0] = 0;