1/*
2* Copyright (c) 2005, Junio C Hamano
3*/
4#include "cache.h"
56
static struct lock_file *lock_file_list;
78
static void remove_lock_file(void)
9{
10while (lock_file_list) {
11if (lock_file_list->filename[0])
12unlink(lock_file_list->filename);
13lock_file_list = lock_file_list->next;
14}
15}
1617
static void remove_lock_file_on_signal(int signo)
18{
19remove_lock_file();
20signal(SIGINT, SIG_DFL);
21raise(signo);
22}
2324
static int lock_file(struct lock_file *lk, const char *path)
25{
26int fd;
27sprintf(lk->filename, "%s.lock", path);
28fd = open(lk->filename, O_RDWR | O_CREAT | O_EXCL, 0666);
29if (0 <= fd) {
30if (!lk->on_list) {
31lk->next = lock_file_list;
32lock_file_list = lk;
33lk->on_list = 1;
34}
35if (lock_file_list) {
36signal(SIGINT, remove_lock_file_on_signal);
37atexit(remove_lock_file);
38}
39if (adjust_shared_perm(lk->filename))
40return error("cannot fix permission bits on %s",
41lk->filename);
42}
43else
44lk->filename[0] = 0;
45return fd;
46}
4748
int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on_error)
49{
50int fd = lock_file(lk, path);
51if (fd < 0 && die_on_error)
52die("unable to create '%s': %s", path, strerror(errno));
53return fd;
54}
5556
int commit_lock_file(struct lock_file *lk)
57{
58char result_file[PATH_MAX];
59int i;
60strcpy(result_file, lk->filename);
61i = strlen(result_file) - 5; /* .lock */
62result_file[i] = 0;
63i = rename(lk->filename, result_file);
64lk->filename[0] = 0;
65return i;
66}
6768
void rollback_lock_file(struct lock_file *lk)
69{
70if (lk->filename[0])
71unlink(lk->filename);
72lk->filename[0] = 0;
73}
74