Skip to content

Instantly share code, notes, and snippets.

@bibhas
Created July 12, 2020 07:08
Show Gist options
  • Save bibhas/54c09920166d2ccf60ec0a628268c01a to your computer and use it in GitHub Desktop.
Save bibhas/54c09920166d2ccf60ec0a628268c01a to your computer and use it in GitHub Desktop.
//
// SUGlobalUpdateLock.h
// Sparkle
//
// Created by Bibhas Acharya on 7/12/20.
// Copyright © 2020 Sparkle Project. All rights reserved.
//
#ifndef SUGLOBALUPDATELOCK_H
#define SUGLOBALUPDATELOCK_H
#import <Foundation/Foundation.h>
@interface SUGlobalUpdateLock : NSObject
+ (SUGlobalUpdateLock *)sharedLock;
- (BOOL)tryLock;
- (void)unlock;
@end
#endif
//
// SUGlobalUpdateLock.m
// Sparkle
//
// Created by Bibhas Acharya on 7/12/20.
// Copyright © 2020 Sparkle Project. All rights reserved.
//
#import "SUGlobalUpdateLock.h"
@implementation SUGlobalUpdateLock
+ (SUGlobalUpdateLock *)sharedLock
{
static dispatch_once_t once;
static SUGlobalUpdateLock *sharedInstance = nil;
dispatch_once(&once, ^{
sharedInstance = [self new];
});
return sharedInstance;
}
- (NSString *)fileLockPath
{
// /var/run/$hostBundleId.Sparkle.pid
NSString *identifier = [[NSBundle mainBundle] bundleIdentifier];
if (identifier == nil) {
// If there's no bundle identifier, use the executable path
identifier = [[[NSBundle mainBundle] executablePath] stringByReplacingOccurrencesOfString:@"/" withString:@"."];
}
return [NSString stringWithFormat:@"/var/run/%@.Sparkle.pid", identifier];
}
- (BOOL)tryLock
{
NSString *fileLockPath = [self fileLockPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager isReadableFileAtPath:fileLockPath]) {
return NO;
}
if ([fileManager fileExistsAtPath:fileLockPath]) {
return NO;
}
if (open(fileLockPath.UTF8String, O_CREAT|O_EXCL, S_IRUSR|S_IWUSR) < 0) {
printf("Couldn't acquire global lock. (err = %s)", strerror(errno));
return NO;
}
return YES;
}
- (void)unlock
{
NSString *fileLockPath = [self fileLockPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if (![fileManager isReadableFileAtPath:fileLockPath]) {
return;
}
if ([fileManager fileExistsAtPath:fileLockPath]) {
return;
}
NSError *error = nil;
[fileManager removeItemAtPath:fileLockPath error:&error];
if (error != nil) {
printf("Unable to unlock!");
}
}
@end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment