Work around failures due to bogus quoting of ^ and {}.
[git/platforms.git] / lockfile.c
blob5301d2879f1af08bf2484b74783790615374760f
1 /*
2 * Copyright (c) 2005, Junio C Hamano
3 */
4 #include "cache.h"
6 static struct lock_file *lock_file_list;
7 static const char *alternate_index_output;
9 static void remove_lock_file(void)
11 pid_t me = getpid();
13 while (lock_file_list) {
14 if (lock_file_list->owner == me &&
15 lock_file_list->filename[0]) {
16 close(lock_file_list->fd);
17 unlink(lock_file_list->filename);
19 lock_file_list = lock_file_list->next;
23 static void remove_lock_file_on_signal(int signo)
25 remove_lock_file();
26 signal(SIGINT, SIG_DFL);
27 raise(signo);
30 static int lock_file(struct lock_file *lk, const char *path)
32 sprintf(lk->filename, "%s.lock", path);
33 lk->fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
34 if (0 <= lk->fd) {
35 if (!lock_file_list) {
36 signal(SIGINT, remove_lock_file_on_signal);
37 atexit(remove_lock_file);
39 lk->owner = getpid();
40 if (!lk->on_list) {
41 lk->next = lock_file_list;
42 lock_file_list = lk;
43 lk->on_list = 1;
45 if (adjust_shared_perm(lk->filename))
46 return error("cannot fix permission bits on %s",
47 lk->filename);
49 else
50 lk->filename[0] = 0;
51 return lk->fd;
54 int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on_error)
56 int fd = lock_file(lk, path);
57 if (fd < 0 && die_on_error)
58 die("unable to create '%s.lock': %s", path, strerror(errno));
59 return fd;
62 int commit_lock_file(struct lock_file *lk)
64 char result_file[PATH_MAX];
65 int i;
66 close(lk->fd);
67 strcpy(result_file, lk->filename);
68 i = strlen(result_file) - 5; /* .lock */
69 result_file[i] = 0;
70 unlink(result_file);
71 i = rename(lk->filename, result_file);
72 lk->filename[0] = 0;
73 return i;
76 int hold_locked_index(struct lock_file *lk, int die_on_error)
78 return hold_lock_file_for_update(lk, get_index_file(), die_on_error);
81 void set_alternate_index_output(const char *name)
83 alternate_index_output = name;
86 int commit_locked_index(struct lock_file *lk)
88 if (alternate_index_output) {
89 int result = rename(lk->filename, alternate_index_output);
90 lk->filename[0] = 0;
91 return result;
93 else
94 return commit_lock_file(lk);
97 void rollback_lock_file(struct lock_file *lk)
99 if (lk->filename[0]) {
100 close(lk->fd);
101 unlink(lk->filename);
103 lk->filename[0] = 0;