Skip to content

Commit

Permalink
Use flock in file logger to coordinate writes with other processes
Browse files Browse the repository at this point in the history
  • Loading branch information
tmolitor-stud-tu authored and ffried committed Sep 4, 2023
1 parent 619d3e2 commit bce8b82
Showing 1 changed file with 10 additions and 0 deletions.
10 changes: 10 additions & 0 deletions Sources/CocoaLumberjack/DDFileLogger.m
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@
#endif

#import <sys/xattr.h>
#import <sys/file.h>
#import <errno.h>
#import <unistd.h>

#import "DDFileLogger+Internal.h"

Expand Down Expand Up @@ -1345,6 +1348,12 @@ - (void)lt_logData:(NSData *)data {
[self willLogMessage:_currentLogFileInfo];
}

// use an advisory lock to coordinate write with other processes
int fd = [handle fileDescriptor];
while(flock(fd, LOCK_EX) != 0) {
NSLogError(@"DDFileLogger: Could not lock logfile, retrying in 1ms: %s (%d)", strerror(errno), errno);
usleep(1000);
}
if (@available(macOS 10.15, iOS 13.0, tvOS 13.0, watchOS 6.0, *)) {
__autoreleasing NSError *error = nil;
BOOL success = [handle seekToEndReturningOffset:nil error:&error];
Expand All @@ -1359,6 +1368,7 @@ - (void)lt_logData:(NSData *)data {
[handle seekToEndOfFile];
[handle writeData:data];
}
flock(fd, LOCK_UN);

if (implementsDeprecatedDidLog) {
#pragma clang diagnostic push
Expand Down

0 comments on commit bce8b82

Please sign in to comment.