Skip to content

Commit ea3cd5c

Browse files
iabervongitster
authored andcommitted
Add a lockfile function to append to a file
This takes care of copying the original contents into the replacement file after the lock is held, so that concurrent additions can't miss each other's changes. [jc: munged to drop mmap in favor of copy_file.] Signed-off-by: Daniel Barkalow <[email protected]> Signed-off-by: Junio C Hamano <[email protected]>
1 parent 2d5c298 commit ea3cd5c

File tree

2 files changed

+29
-0
lines changed

2 files changed

+29
-0
lines changed

cache.h

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -391,6 +391,7 @@ struct lock_file {
391391
char filename[PATH_MAX];
392392
};
393393
extern int hold_lock_file_for_update(struct lock_file *, const char *path, int);
394+
extern int hold_lock_file_for_append(struct lock_file *, const char *path, int);
394395
extern int commit_lock_file(struct lock_file *);
395396

396397
extern int hold_locked_index(struct lock_file *, int);

lockfile.c

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -160,6 +160,34 @@ int hold_lock_file_for_update(struct lock_file *lk, const char *path, int die_on
160160
return fd;
161161
}
162162

163+
int hold_lock_file_for_append(struct lock_file *lk, const char *path, int die_on_error)
164+
{
165+
int fd, orig_fd;
166+
167+
fd = lock_file(lk, path);
168+
if (fd < 0) {
169+
if (die_on_error)
170+
die("unable to create '%s.lock': %s", path, strerror(errno));
171+
return fd;
172+
}
173+
174+
orig_fd = open(path, O_RDONLY);
175+
if (orig_fd < 0) {
176+
if (errno != ENOENT) {
177+
if (die_on_error)
178+
die("cannot open '%s' for copying", path);
179+
close(fd);
180+
return error("cannot open '%s' for copying", path);
181+
}
182+
} else if (copy_fd(orig_fd, fd)) {
183+
if (die_on_error)
184+
exit(128);
185+
close(fd);
186+
return -1;
187+
}
188+
return fd;
189+
}
190+
163191
int close_lock_file(struct lock_file *lk)
164192
{
165193
int fd = lk->fd;

0 commit comments

Comments
 (0)