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->next) {
31lk->next = lock_file_list;
32lock_file_list = lk;
33signal(SIGINT, remove_lock_file_on_signal);
34atexit(remove_lock_file);
35}
36if (adjust_shared_perm(lk->filename))
37return error("cannot fix permission bits on %s",
38lk->filename);
39}
40return fd;
41}
4243
int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on_error)
44{
45int fd = lock_file(lk, path);
46if (fd < 0 && die_on_error)
47die("unable to create '%s': %s", path, strerror(errno));
48return fd;
49}
5051
int commit_lock_file(struct lock_file *lk)
52{
53char result_file[PATH_MAX];
54int i;
55strcpy(result_file, lk->filename);
56i = strlen(result_file) - 5; /* .lock */
57result_file[i] = 0;
58i = rename(lk->filename, result_file);
59lk->filename[0] = 0;
60return i;
61}
6263
void rollback_lock_file(struct lock_file *lk)
64{
65if (lk->filename[0])
66unlink(lk->filename);
67lk->filename[0] = 0;
68}
69