public override void Lock(bool nonBlock = false) { if (LockedCount == 0) { IO.MakeDirIfNotExists(Env.UnixMutantDir); UnixPermissions perm = UnixPermissions.S_IRUSR | UnixPermissions.S_IWUSR | UnixPermissions.S_IRGRP | UnixPermissions.S_IWGRP | UnixPermissions.S_IROTH | UnixPermissions.S_IWOTH; IntPtr fd = UnixApi.Open(Filename, UnixApi.OpenFlags.O_CREAT | UnixApi.OpenFlags.O_CLOEXEC, (int)perm); if (fd.ToInt64() < 0) { throw new IOException("Open failed."); } try { if (UnixApi.FLock(fd, UnixApi.LockOperations.LOCK_EX | (nonBlock ? UnixApi.LockOperations.LOCK_NB : 0)) == -1) { throw new IOException("FLock failed."); } } catch { UnixApi.Close(fd); throw; } this.FileHandle = fd; LockedCount++; } }
public static void DeleteUnusedMutantFiles() { if (Env.IsUnix == false) { return; } try { string[] fileFullPathList = Directory.GetFiles(Env.UnixMutantDir); foreach (string fileFullPath in fileFullPathList) { try { if (fileFullPath.EndsWith(Extension, StringComparison.OrdinalIgnoreCase)) { UnixPermissions perm = UnixPermissions.S_IRUSR | UnixPermissions.S_IWUSR | UnixPermissions.S_IRGRP | UnixPermissions.S_IWGRP | UnixPermissions.S_IROTH | UnixPermissions.S_IWOTH; bool okToDelete = false; IntPtr fd = UnixApi.Open(fileFullPath, UnixApi.OpenFlags.O_CREAT | UnixApi.OpenFlags.O_CLOEXEC, (int)perm); if (fd.ToInt64() >= 0) { try { if (UnixApi.FLock(fd, UnixApi.LockOperations.LOCK_EX | UnixApi.LockOperations.LOCK_NB) != -1) { okToDelete = true; } } finally { try { UnixApi.FLock(fd, UnixApi.LockOperations.LOCK_UN); } catch { } try { UnixApi.Close(fd); } catch { } } } if (okToDelete) { try { File.Delete(fileFullPath); } catch { } } } } catch { } } } catch { } }