Skip to content

Instantly share code, notes, and snippets.

@pgtwitter
Created May 1, 2025 11:33
Show Gist options
  • Save pgtwitter/5c8560b14166d946f53a4bc09eab0a68 to your computer and use it in GitHub Desktop.
Save pgtwitter/5c8560b14166d946f53a4bc09eab0a68 to your computer and use it in GitHub Desktop.
/tmp/lockfileを確認し,存在していないもしくは一時間以上前の作成ならロックファイルを作成もしくは更新して正常終了0.ファイルが存在し一時間以内なら有効なロックファイルとして正常終了0.なにかしら問題があれば異常終了1.Grok3作.
// clang -fobjc-arc -framework Foundation lockfile.m -o lockfile
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
// ロックファイルのパス
NSString *lockFilePath = @"/tmp/lockfile";
// NSFileManagerのインスタンス
NSFileManager *fileManager = [NSFileManager defaultManager];
// 現在時刻
NSDate *now = [NSDate date];
// ファイルの属性を取得するためのエラー変数
NSError *error = nil;
if ([fileManager fileExistsAtPath:lockFilePath]) {
// ファイルの属性を取得(作成日時)
NSDictionary *attributes = [fileManager attributesOfItemAtPath:lockFilePath error:&error];
if (error) {
NSLog(@"属性の取得に失敗しました: %@", error.localizedDescription);
return 1;
}
// ファイルの作成日時を取得
NSDate *creationDate = attributes[NSFileCreationDate];
if (!creationDate) {
NSLog(@"作成日時の取得に失敗しました");
return 1;
}
// 現在時刻と作成日時の差を計算(秒単位)
NSTimeInterval timeDifference = [now timeIntervalSinceDate:creationDate];
if (timeDifference <= 3600) { // 1時間(3600秒)以内
NSLog(@"有効なロックファイルです(作成時刻: %@)", creationDate);
return 0;
} else {
NSLog(@"ロックファイルが1時間以上経過しています(作成時刻: %@)。更新します。", creationDate);
// 古いファイルを削除
if (![fileManager removeItemAtPath:lockFilePath error:&error]) {
NSLog(@"古いロックファイルの削除に失敗しました: %@", error.localizedDescription);
return 1;
}
}
} else {
NSLog(@"ロックファイルが存在しません。新規作成します。");
}
// 新しいロックファイルを作成
BOOL success = [fileManager createFileAtPath:lockFilePath
contents:nil
attributes:nil];
if (success) {
NSLog(@"ロックファイルを作成/更新しました: %@", lockFilePath);
} else {
NSLog(@"ロックファイルの作成/更新に失敗しました");
return 1;
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment