public override void Lock(bool nonBlock = false) { if (LockedCount == 0) { IO.MakeDirIfNotExists(Env.UnixMutantDir); UnixApi.Permissions perm = UnixApi.Permissions.S_IRUSR | UnixApi.Permissions.S_IWUSR | UnixApi.Permissions.S_IRGRP | UnixApi.Permissions.S_IWGRP | UnixApi.Permissions.S_IROTH | UnixApi.Permissions.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."); } if (UnixApi.FLock(fd, UnixApi.LockOperations.LOCK_EX | (nonBlock ? UnixApi.LockOperations.LOCK_NB : 0)) == -1) { throw new IOException("FLock failed."); } 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)) { UnixApi.Permissions perm = UnixApi.Permissions.S_IRUSR | UnixApi.Permissions.S_IWUSR | UnixApi.Permissions.S_IRGRP | UnixApi.Permissions.S_IWGRP | UnixApi.Permissions.S_IROTH | UnixApi.Permissions.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 { } }