private void InitMutex() { string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); string mutexId = string.Format("Global\\{{{0}}}", appGuid); this.mutex = new Mutex(false, mutexId); MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); this.mutex.SetAccessControl(securitySettings); }
// Mutex code from http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c public static void PreloadUnmanagedLibraries(string hash, string tempBasePath, IEnumerable<string> libs, Dictionary<string, string> checksums) { var mutexId = string.Format("Global\\Costura{0}", hash); using (var mutex = new Mutex(false, mutexId)) { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); var hasHandle = false; try { try { hasHandle = mutex.WaitOne(60000, false); if (hasHandle == false) throw new TimeoutException("Timeout waiting for exclusive access"); } catch (AbandonedMutexException) { hasHandle = true; } var bittyness = IntPtr.Size == 8 ? "64" : "32"; CreateDirectory(Path.Combine(tempBasePath, bittyness)); InternalPreloadUnmanagedLibraries(tempBasePath, libs, checksums); } finally { if (hasHandle) mutex.ReleaseMutex(); } } }
static void Main(string[] args) { string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); string mutexId = string.Format("Global\\{{{0}}}", appGuid); string settingsProfileName = GetSettingsProfileNameFromArgs(args)?.Trim(); if (!string.IsNullOrEmpty(settingsProfileName) && settingsProfileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { // settingsProfileName contains chars not valid for a filename MessageBox.Show(settingsProfileName + " is an invalid settings profile name", "Error"); return; } if (AllowMultiInstance) #pragma warning disable 162 { Run(settingsProfileName); } #pragma warning restore 162 else #pragma warning disable 162 { using (var mutex = new Mutex(false, mutexId)) { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); var hasHandle = false; try { try { hasHandle = mutex.WaitOne(2000, false); if (hasHandle == false) { MessageBox.Show("osu!StreamCompanion is already running.", "Error"); return; } } catch (AbandonedMutexException) { hasHandle = true; } Run(settingsProfileName); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } } #pragma warning restore 162 }
/// <summary> /// /// </summary> /// <param name="mutexName">互斥对象的名称</param> /// <param name="tryCleanAbandoned">是否尝试释放已经存在的被放弃的mutex</param> /// <param name="mutex">成功时返回的互斥对象</param> /// <param name="errcode">错误代码,0无错误,1无法创建互斥对象,2互斥对象存在,无法获取访问权限,3互斥对象正被其他线程占用,4有被弃用的互斥对象,被本方法释放,5互斥对象已存在</param> /// <returns></returns> private static bool TryEnter(string mutexName, bool tryCleanAbandoned, out Mutex mutex, out int errcode) { mutex = null; errcode = 0; // 无错误 if (string.IsNullOrEmpty(mutexName)) { return(false); } Mutex m = null; bool doesNotExist = false; bool unauthorized = false; bool mutexWasCreated = false; bool hasAccessException = false; try { // 尝试打开现有的 m = Mutex.OpenExisting(mutexName); } catch (WaitHandleCannotBeOpenedException) { // 不存在 doesNotExist = true; } catch (UnauthorizedAccessException) { // 没有访问权限 unauthorized = true; } // 如果不存在则创建 if (doesNotExist) { MutexSecurity mSec = null; try { string user = Environment.UserDomainName + "\\" + Environment.UserName; mSec = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Deny); mSec.AddAccessRule(rule); rule = new MutexAccessRule(user, MutexRights.ReadPermissions | MutexRights.ChangePermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); } catch { hasAccessException = true; } if (hasAccessException) { m = new Mutex(true, mutexName, out mutexWasCreated); } else { m = new Mutex(true, mutexName, out mutexWasCreated, mSec); } if (mutexWasCreated) { mutex = m; return(true); } else { errcode = 1; //无法创建对象 return(false); } } // 尝试增加访问权限 if (unauthorized) { try { m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions); MutexSecurity mSec = m.GetAccessControl(); string user = Environment.UserDomainName + "\\" + Environment.UserName; MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Deny); mSec.RemoveAccessRule(rule); rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); mSec.AddAccessRule(rule); m.SetAccessControl(mSec); m = Mutex.OpenExisting(mutexName); } catch (UnauthorizedAccessException) { errcode = 2;// 无法获取访问权限 return(false); } catch (Exception) { errcode = 3;// mutex对象正被其他线程占用 return(false); } } // 对于已经存在的具备访问权限了 if (tryCleanAbandoned) { try { // 尝试立刻获取控制 bool waitSuccess = m.WaitOne(0); // 不排除有能正好获取到访问权限的 if (!waitSuccess) { errcode = 3;// mutex对象正被其他线程占用 } else { mutex = m; } return(waitSuccess); } // 如果发现是被弃用的 catch (AbandonedMutexException) { m.ReleaseMutex(); errcode = 4; // 有被弃用的mutex对象 return(false); } } else { errcode = 5; // mutex对象存在,用户未尝试释放 return(false); } }
static void Main(string[] args) { bool noAudio = false; bool multipleInstanceMode = false; List <string> unknownStartupParams = new List <string>(); for (int arg = 0; arg < args.Length; arg++) { string argument = args[arg].ToUpper(); switch (argument) { case "-NOAUDIO": // TODO fix throw new NotImplementedException("-NOAUDIO is currently not implemented, please run the client without it."); case "-MULTIPLEINSTANCE": multipleInstanceMode = true; break; default: unknownStartupParams.Add(argument); break; } } StartupParams parameters = new StartupParams(noAudio, multipleInstanceMode, unknownStartupParams); if (multipleInstanceMode) { // Proceed to client startup PreStartup.Initialize(parameters); return; } // We're a single instance application! // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes( typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // Global prefix means that the mutex is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); using (var mutex = new Mutex(false, mutexId, out bool createdNew, securitySettings)) { var hasHandle = false; try { try { hasHandle = mutex.WaitOne(8000, false); if (hasHandle == false) { throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { hasHandle = true; } catch (TimeoutException) { return; } // Proceed to client startup PreStartup.Initialize(parameters); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } }
/// <summary> /// <para>Starts a process running Excel and sets the /// <see cref="Microsoft.Hpc.Excel.ExcelDriver.App" /> and /// <see cref="Microsoft.Hpc.Excel.ExcelDriver.ExcelProcess" /> properties.</para> /// </summary> /// <remarks> /// <para>You can user the /// <see cref="Microsoft.Hpc.Excel.ExcelDriver.App" /> and /// <see cref="Microsoft.Hpc.Excel.ExcelDriver.ExcelProcess" /> properties to continue to interact with Excel.</para> /// </remarks> /// <seealso cref="Microsoft.Hpc.Excel.ExcelDriver.App" /> /// <seealso cref="Microsoft.Hpc.Excel.ExcelDriver.ExcelProcess" /> public void LaunchExcelProcess() { lock (this.launchExcelLock) { if (this.ExcelProcess != null) { throw new InvalidOperationException(Resources.ExcelDriver_LaunchExcelOnce); } // Create the mutex. This function is only called once and the mutex is only needed here, so it's robust. bool createdNew = false; // Give access to mutex to everyone SecurityIdentifier sid = new SecurityIdentifier(System.Security.Principal.WellKnownSidType.WorldSid, null); MutexSecurity mutSec = new MutexSecurity(); MutexAccessRule mutRule = new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow); mutSec.AddAccessRule(mutRule); // Create mutex with full control for everyone. Doesn't matter if mutex is created new. this.excelLaunchMutex = new Mutex(false, "47FFDA0F-26D3-49fa-8E65-FC7590EFB95F", out createdNew, mutSec); bool ownMutex = false; Tracing.WriteDebugTextInfo(Tracing.ComponentId.ExcelDriver, Resources.ExcelDriver_OpeningExcel); try { this.basher = new PopupBasher(); // Create an Excel COM Server process so that it'll populate the ROT ProcessStartInfo info = new ProcessStartInfo(); info.FileName = "excel.exe"; info.Arguments = @"/automation -Embedding"; try { // Take lock on global mutex to ensure 'new ApplicationClass()' returns application // associated with the created excel process. this.excelLaunchMutex.WaitOne(); ownMutex = true; } catch (AbandonedMutexException ex) { // This mutex will only be abandoned on hard faults. // In the case of a SOA service, this can happen when the job is cancelled or preempted. // In any case, this should not produce an unstable state. Tracing.WriteDebugTextWarning(Tracing.ComponentId.ExcelDriver, ex.ToString()); } // Start the process and wait until it is usable. try { this.ExcelProcess = new Process(); this.ExcelProcess.StartInfo = info; this.ExcelProcess.Start(); } catch (System.ComponentModel.Win32Exception) { // If there is a problem starting the excel process, null out the process and rethrow this.ExcelProcess = null; throw; } Process currentProcess = Process.GetCurrentProcess(); this.SwitchToWindow(currentProcess.MainWindowHandle); this.SwitchToWindow(this.ExcelProcess.MainWindowHandle); this.ExcelProcess.WaitForInputIdle(); // Let popupbasher know what the process ID for Excel is PopupBasher.ExcelProcessId = this.ExcelProcess.Id; // Creates a new Excel Application this.App = new ApplicationClass(); } finally { // Release the global mutex if (ownMutex) { this.excelLaunchMutex.ReleaseMutex(); } } this.App.Visible = true; // Makes Excel visible to the user. this.App.DisplayAlerts = false; // Don't pop up message about other users using the same workbook } }
public static void Main() { // Create a string representing the current user. string user = Environment.UserDomainName + "\\" + Environment.UserName; // Create a security object that grants no access. MutexSecurity mSec = new MutexSecurity(); // Add a rule that grants the current user the // right to enter or release the mutex. MutexAccessRule ruleA = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); mSec.AddAccessRule(ruleA); // Add a rule that denies the current user the // right to change permissions on the mutex. MutexAccessRule rule = new MutexAccessRule(user, MutexRights.ChangePermissions, AccessControlType.Deny); mSec.AddAccessRule(rule); // Display the rules in the security object. ShowSecurity(mSec); // Add a rule that allows the current user the // right to read permissions on the mutex. This rule // is merged with the existing Allow rule. rule = new MutexAccessRule(user, MutexRights.ReadPermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); ShowSecurity(mSec); // Attempt to remove the original rule (granting // the right to enter or release the mutex) with // RemoveAccessRuleSpecific. The removal fails, // because the right to read the permissions on the // mutex has been added to the rule, so that it no // longer matches the original rule. Console.WriteLine("Attempt to use RemoveAccessRuleSpecific on the original rule."); mSec.RemoveAccessRuleSpecific(ruleA); ShowSecurity(mSec); // Create a rule that grants the current user // the right to enter or release the mutex, and // to read permissions. Use this rule to remove // the Allow rule for the current user. Console.WriteLine("Use RemoveAccessRuleSpecific with the correct rights."); rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify | MutexRights.ReadPermissions, AccessControlType.Allow); mSec.RemoveAccessRuleSpecific(rule); ShowSecurity(mSec); }
static void Main(String[] args) { // prevent multiple instances: code from https://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly(). GetCustomAttributes(typeof(GuidAttribute), false). GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid , null) , MutexRights.FullControl , AccessControlType.Allow ); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired hasHandle = true; } // Perform your work here. log4net.Config.XmlConfigurator.Configure(); // log version number Assembly asm = Assembly.GetExecutingAssembly(); FileVersionInfo fvi = FileVersionInfo.GetVersionInfo(asm.Location); log.Info($"Keyboard2Xinput v{fvi.ProductVersion}"); // parse args if (args.Length > 1) { MessageBox.Show("Too many arguments. Usage: Keyboard2XinputGui [mappingfile]", "Keyboard2Xinput", MessageBoxButtons.OK, MessageBoxIcon.Error); } else { String mappingFile = null; if (args.Length > 0) { mappingFile = args[0]; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); AppDomain currentDomain = AppDomain.CurrentDomain; currentDomain.UnhandledException += new UnhandledExceptionEventHandler(MyHandler); Application.ApplicationExit += new EventHandler(OnApplicationExit); gui = new Keyboard2XinputGui(mappingFile); // Run() without parameter to not show the form at launch Application.Run(); //Application.Run(gui); } } finally { // edited by acidzombie24, added if statement if (hasHandle) { mutex.ReleaseMutex(); } } } }
public void RemoveAccessRuleAll(MutexAccessRule rule);
public static void Main(string[] args) { try { //Allows us to group device runs for logging purposes RunIdentifier = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now); ParallelProcessObserver = new ProcessObserver(); Trace.Listeners.Add(new TextWriterTraceListener("ParallelDeviceOutput.log", "myListener")); /*Args Note: * Having difficulty sending in separated args from Powershell * when there are spaces in the arguments, they split up the where statment. * Need to do some special handling to get around this. Using an "^" to split incoming args * * Expecting possiblity of: a:TheTestAssembly.dll^w:category==xyz AND category==123 */ var joinedArgs = string.Join(" ", args); Console.WriteLine("arguments are: " + joinedArgs); var argsSplit = string.IsNullOrWhiteSpace(joinedArgs) ? null : joinedArgs.Split('^'); string assemblyArgs = ""; string whereFilter = ""; if (argsSplit != null && argsSplit.Length > 0) { foreach (string arg in argsSplit) { Console.WriteLine("Reading Arg:" + arg); if (arg.StartsWith("a:")) { assemblyArgs = arg.Substring(2); } if (arg.StartsWith("w:")) { whereFilter = arg.Substring(2); } } } else { Console.WriteLine("No assembly passed in so using VSTSDigitalDemoTests.dll"); assemblyArgs = "VSTSDigitalDemoTests.dll"; } //Get the devices to run for string currentPath = Directory.GetCurrentDirectory(); string baseProjectPath = Path.GetFullPath(Path.Combine(currentPath, @"..\..\..\")); ParameterRetriever retriever = new ParameterRetriever(); PerfectoTestParams testParams = retriever.GetVSOExecParam(baseProjectPath, true); if (testParams.Devices.Count < 0) { Console.WriteLine("No devices found from JSON config file."); #if DEBUG Console.ReadKey(); #endif return; } //Now create a mutex so that this console app can only be run 1 at a time. // get application GUID as defined in AssemblyInfo.cs string appGuid = "PerfectoParallelRunner-82678dc5439649959b6e0b686efb1222"; // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { var hasHandle = false; try { try { hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { throw new TimeoutException("Make sure another Test Process isn't already running."); } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, it will still get acquired hasHandle = true; } // Perform your work here. RunParallelExecutions(assemblyArgs, whereFilter, testParams); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); #if DEBUG Console.ReadKey(); #endif throw; } }
static void Main(string[] args) { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); using (var mutex = new Mutex(false, mutexId)) { // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(500, false); if (hasHandle == false) { if (args.Count() == 1) { if (args[0] == "update") { //TODO: send message to pipe NamedPipeClientStream pipe = new NamedPipeClientStream(".", "NXTLibTesterGUI_forceupdatepipe", PipeDirection.Out); StreamWriter sw = new StreamWriter(pipe); pipe.Connect(); sw.AutoFlush = true; sw.WriteLine("Force Update Now!"); pipe.WaitForPipeDrain(); pipe.Dispose(); } return; } MessageBox.Show("Application already running! Close the other instance and try again.", "Application Running", MessageBoxButtons.OK, MessageBoxIcon.Error); return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } FindNXT.updatewaiting = false; if (args.Count() == 1) { if (args[0] == "update") { FindNXT.updatewaiting = true; } } // Perform your work here. Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FindNXT()); } finally { // edited by acidzombie24, added if statemnet if (hasHandle) { mutex.ReleaseMutex(); } } } }
protected override void OnStartup(StartupEventArgs e) { try { InitNotificationIcon(); //DCSFlightpanels.exe OpenProfile="C:\Users\User\Documents\Spitfire_Saitek_DCS_Profile.bindings" //DCSFlightpanels.exe OpenProfile='C:\Users\User\Documents\Spitfire_Saitek_DCS_Profile.bindings' //1 Check for start arguments. //2 If argument and profile exists close running instance, start this with profile chosen var closeCurrentInstance = false; try { if (e.Args.Length > 0 && e.Args[0].Contains("OpenProfile") && e.Args[0].Contains("=")) { var array = e.Args[0].Split(new[] { '=' }, StringSplitOptions.RemoveEmptyEntries); if (array[0].Equals("OpenProfile") && File.Exists(array[1].Replace("\"", "").Replace("'", ""))) { Settings.Default.LastProfileFileUsed = array[1].Replace("\"", "").Replace("'", ""); Settings.Default.RunMinimized = true; closeCurrentInstance = true; } else { MessageBox.Show("Invalid startup arguments." + Environment.NewLine + array[0] + Environment.NewLine + array[1]); } } } catch (Exception ex) { MessageBox.Show("Error processing startup arguments." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); } // get application GUID as defined in AssemblyInfo.cs var appGuid = "{23DB8D4F-D76E-4DF4-B04F-4F4EB0A8E992}"; // unique id for global mutex - Global prefix means it is global to the machine string mutexId = "Global\\" + appGuid; // Need a place to store a return value in Mutex() constructor call var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); _mutex = new Mutex(false, mutexId, out var createdNew, securitySettings); _hasHandle = false; try { _hasHandle = _mutex.WaitOne(2000, false); } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired //_hasHandle = true; } if (!closeCurrentInstance && !_hasHandle) { MessageBox.Show("DCSFlightpanels is already running.."); Current.Shutdown(0); Environment.Exit(0); } if (closeCurrentInstance && !_hasHandle) { foreach (var process in Process.GetProcesses()) { if (process.ProcessName.Equals(Process.GetCurrentProcess().ProcessName) && process.Id != Process.GetCurrentProcess().Id) { process.Kill(); break; } } // Wait for process to close Thread.Sleep(2000); } base.OnStartup(e); } catch (Exception ex) { MessageBox.Show("Error starting DCSFlightpanels." + Environment.NewLine + ex.Message + Environment.NewLine + ex.StackTrace); Current.Shutdown(0); Environment.Exit(0); } }
static void Main() { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly(). GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique ID for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; // to add example of setting up security for multi-user usage // to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // to prevent race condition on security settings using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { var hasHandle = false; try { try { // 만약 global mutex가 잡혀 있으면 기다리지 않고 즉시 종료합니다. hasHandle = mutex.WaitOne(0, false); if (hasHandle == false) { MessageBox.Show("이미 실행 중인 프로그램이 있습니다.", "ChordingCoding", MessageBoxButtons.OK, MessageBoxIcon.Warning); throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired hasHandle = true; } // 아래 코드는 프로그램이 단독으로 실행할 때 수행할 명령들입니다. Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Form1을 실행합니다. MainForm form = new MainForm(); Application.Run(form); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } }
private static void Main(string[] args) { // get application GUID as defined in AssemblyInfo.cs var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value; // unique id for global mutex - Global prefix means it is global to the machine var mutexId = $"Global\\{{{appGuid}}}"; // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen using (var mutex = new Mutex(false, mutexId, out bool _, securitySettings)) { // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(0, false); if (hasHandle == false) { MessageBox.Show("The application is already running"); //throw new TimeoutException("Timeout waiting for exclusive access"); return; } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired hasHandle = true; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new Form1(args)); } finally { // edited by acidzombie24, added if statement if (hasHandle) { mutex.ReleaseMutex(); } } } }
static void Main(string[] args) { string inputUrl = null; bool silent = false; // Process command line arguments. foreach (string arg in args) { /* Valid arguments: * /silent +silent * /auto +auto */ if (arg.StartsWith("/") || arg.StartsWith("+")) { string option = arg.Substring(1); if (option.Equals("silent", StringComparison.OrdinalIgnoreCase) || option.Equals("auto", StringComparison.OrdinalIgnoreCase)) { silent = true; } } else if (inputUrl == null && Util.IsValidUrl(arg)) { inputUrl = arg; } } // Get the application GUID defined in AssemblyInfo.cs string guid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // id for global mutex (global to machine) string mutexId = string.Format("Global\\{{{0}}}", guid); bool createdNew = false; MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); // Only allow a single instance of YDL-UI to run. using (Mutex mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { bool hasHandle = false; try { try { hasHandle = mutex.WaitOne(250, false); // Timeout after 250ms. if (!hasHandle) // Application is already running. { if (inputUrl != null) // A url was provided, send it to the currently running instance of YDL-UI. { SendUrl(inputUrl, silent); } else { MessageBox.Show("The application is already running.", Application.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Exclamation); } Environment.Exit(0); return; } } catch (AbandonedMutexException) { hasHandle = true; // The mutex was abandoned in another process, it will still get acquired. } // Start application normally. Application.Run(new FormMain(inputUrl, silent)); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } }
public void AddAccessRule(MutexAccessRule rule);
private static void StartOrSignal(Action Run) { // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format(useGlobalMutex ? "Global\\{{{0}}}" : "{{{0}}}", appGuid); string SingleAppComEventName = mutexId + "_event"; BackgroundWorker singleAppComThread = null; EventWaitHandle threadComEvent = null; using (var mutex = new Mutex(false, mutexId)) { var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); var hasHandle = false; try { try { hasHandle = mutex.WaitOne(1000, false); if (hasHandle == false) { Debug.WriteLine("Instance already running, timeout expired"); threadComEvent = EventWaitHandle.OpenExisting(SingleAppComEventName); threadComEvent.Set(); // signal the other instance. threadComEvent.Close(); return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } threadComEvent = new EventWaitHandle(false, EventResetMode.AutoReset, SingleAppComEventName); singleAppComThread = new BackgroundWorker(); singleAppComThread.WorkerReportsProgress = false; singleAppComThread.WorkerSupportsCancellation = true; singleAppComThread.DoWork += (object sender, DoWorkEventArgs e) => { BackgroundWorker worker = sender as BackgroundWorker; WaitHandle[] waitHandles = new WaitHandle[] { threadComEvent }; while (!worker.CancellationPending && !_Closing) { // check every second for a signal. if (WaitHandle.WaitAny(waitHandles, 1000) == 0) { // The user tried to start another instance. We can't allow that, // so bring the other instance back into view and enable that one. // That form is created in another thread, so we need some thread sync magic. if (OnAdditionalInstanceSignal != null) { OnAdditionalInstanceSignal(sender, new EventArgs()); } } } }; singleAppComThread.RunWorkerAsync(); Run(); singleAppComThread.CancelAsync(); while (singleAppComThread.IsBusy) { Thread.Sleep(50); } threadComEvent.Close(); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } }
public void ResetAccessRule(MutexAccessRule rule);
static void ThreadFunc() { bool bCreated = false; var user = "******"; var rule = new MutexAccessRule(user, MutexRights.FullControl, AccessControlType.Allow ); var mSecurity = new MutexSecurity(); mSecurity.AddAccessRule(rule); Mutex m = new Mutex(true, Program.mutex_name, out bCreated, mSecurity); if (!bCreated) { Console.WriteLine("Waiting... {0}", Thread.CurrentThread.ManagedThreadId); m.WaitOne(); Console.WriteLine("Acquired Mutex! {0}", Thread.CurrentThread.ManagedThreadId); } System.Threading.Thread.Sleep(5 * 1000); m.ReleaseMutex(); m.Close(); }
bool Start() { bool success = false; // Delegate for the control handler to handle console break and close events ConsoleCtrlDelegate console_ctrl_delegate = null; // Event window to handle console-minimize events ConsoleEventWindow console_event_window = null; // Event watcher to handle WMI brightness events ManagementEventWatcher watcher = null; /* If it was requested to hide the console do that first, since doing anything else * first would mean the console is more likely to be seen (ie flicker) even if it should * be hidden. */ if (we_own_the_console) { if (opt_hide_on_start || (opt_hide_on_minimize && IsIconic(GetConsoleWindow()))) { MinimizeAndHideWindow(GetConsoleWindow()); } Console.BufferHeight = 10000; } else { if (opt_hide_on_start || opt_hide_on_minimize) { Console.WriteLine( "WARNING: " + ProgName + " isn't running in its own console window, so " + "the options that were specified to hide the console are being ignored.\n" ); } } string title = ProgName + ": Sync AC & DC brightness"; Console.Title = title; Console.WriteLine(title); Console.WriteLine(""); Console.WriteLine("Use option /? for usage information."); Console.WriteLine(""); // Synchronization used by other threads to run code in this main UI thread UISyncContext = new WindowsFormsSynchronizationContext(); SynchronizationContext.SetSynchronizationContext(UISyncContext); // Pop our console to the front when we're signaled by a secondary instance ThreadPool.RegisterWaitForSingleObject(RestoreConsoleEvent, delegate { IntPtr console = GetConsoleWindow(); ShowWindow(console, SW_MINIMIZE); ShowWindow(console, SW_RESTORE); }, null, -1, false); if (we_own_the_console) { Tray_Create(); console_ctrl_delegate = new ConsoleCtrlDelegate(ConsoleCtrlHandlerRoutine); SetConsoleCtrlHandler(console_ctrl_delegate, true); if (opt_hide_on_minimize) { console_event_window = new ConsoleEventWindow(GetConsoleWindow()); Console.Title += " (minimize-to-tray enabled)"; /* If the console window is already minimized then emulate the notification to * the event window. It's important to send this so that the event window is * hidden in a way that the window manager unhides it when the console window is * restored. * * It's possible to have a race condition here, for example the console window * is minimized during or after the event window is created but before this * code, so the event window may receive the message twice. That is fine, the * window manager tracks the event window status properly and it will still * unhide the event window properly when the console window is restored. */ if (IsIconic(GetConsoleWindow())) { //Console.Beep(300, 250); SendMessage(console_event_window.Handle, WM_SHOWWINDOW, NULL, (IntPtr)SW_PARENTCLOSING); } } } // Global mutex to handle multiple sessions running this program at the same time if (SyncBrightnessMutex == null) { SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.WorldSid, null); MutexAccessRule rule = new MutexAccessRule(sid, MutexRights.FullControl, AccessControlType.Allow); MutexSecurity sec = new MutexSecurity(); sec.AddAccessRule(rule); bool created_new = false; SyncBrightnessMutex = new Mutex(false, SyncBrightnessMutexName, out created_new, sec); } //todo:Is there a way to get brightness changed event using Win32 API without WMI? string scope = @"\\localhost\root\WMI"; string query = "SELECT * FROM WmiMonitorBrightnessEvent"; watcher = new ManagementEventWatcher(scope, query); watcher.EventArrived += new EventArrivedEventHandler(OnBrightnessChanged); Console.WriteLine("Monitoring brightness change..."); SyncBrightness(); // Start monitoring brightness events. The watcher calls SyncBrightness when necessary. try { watcher.Start(); } // Check for access denied, for example a Guest account can't monitor brightness events. catch (UnauthorizedAccessException) { Console.Error.WriteLine("\nError: Can't monitor brightness events, access denied."); goto Cleanup; } #if DEBUG // Force GC to help coax out any bugs that otherwise wouldn't be apparent. GC.Collect(); GC.WaitForPendingFinalizers(); GC.Collect(); #endif // Start the message loop to handle synchronization events and window messsages. Application.Run(); // Application.Run() returns due to Application.Exit(). // Currently that only happens at the user's request. success = true; Cleanup: /* Do a graceful cleanup. * Note since this is a console application if the user closes the console window then * this code is never reached. Refer to ConsoleCtrlHandlerRoutine. */ if (console_ctrl_delegate != null) { SetConsoleCtrlHandler(console_ctrl_delegate, false); } if (Tray != null) { Tray.Dispose(); } if (watcher != null) { watcher.Stop(); } GC.KeepAlive(console_event_window); return(success ? true : false); }
private static void Main(string[] argc) { try { if (!AppHelper.PreInit()) { return; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Assembly execAssembly = Assembly.GetExecutingAssembly(); AppHelper.GUID = ((GuidAttribute)execAssembly.GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value; string mutexId = string.Format("Global\\{{{0}}}", AppHelper.GUID); bool createdNew; MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); using (Mutex mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { bool hasHandle = false; try { try { hasHandle = mutex.WaitOne(3000, false); if (hasHandle == false) { if (AppHelper.ARGS.FirstOrDefault(x => x.ToLower() == "-f") != null) { AppHelper.CreateMessage("Выполнен запуск по требованию", MessageType.Information); NamedPipeListener <string> .SendMessage(AppHelper.ProductName, "force"); } else { MessageBox.Show("Программа уже запущена", AppHelper.ProductName, MessageBoxButtons.OK, MessageBoxIcon.Warning); } return; } } catch (AbandonedMutexException err) { AppHelper.CreateMessage("Ошибка синхронизации Mutex: " + err.ToString(), MessageType.Error, true); hasHandle = true; } if (CheckDependencies()) { if (!SecurityHelper.IsAdministrator()) { AppHelper.CreateMessage("Программу необходимо запускать от имени администратора", MessageType.Error, true); return; } Application.Run(new MainForm()); } else { AppHelper.CreateMessage("Неверная версия Feodosiya.Lib.dll. Необходимая версия: >=" + MinFeodosiyaLibVer, MessageType.Error, true); return; } } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } } catch (Exception ex) { AppHelper.CreateMessage(ex.ToString(), MessageType.Error, true); } }
private static void Main(string[] args) { Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; #region Logging Log.Logger = new LoggerConfiguration() #if DEBUG .MinimumLevel.Debug() #else .MinimumLevel.Information() #endif .WriteTo.Console() .WriteTo.RollingFile("Logs\\Shibari.Dom.Server-{Date}.log") .CreateLogger(); #endregion #region Global exception handler AppDomain.CurrentDomain.UnhandledException += (sender, eventArgs) => { Log.Fatal("Unhandled exception: {Exception}", (Exception)eventArgs.ExceptionObject); }; #endregion Log.Information("Launching Shibari, version: {Version}", Assembly.GetExecutingAssembly().GetName().Version); #region Self-Unblocking var domRoot = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) ?? "."; var rootDrive = new DriveInfo(domRoot); // ADS is only present on NTFS formatted drives if (rootDrive.DriveFormat.Equals("NTFS", StringComparison.InvariantCultureIgnoreCase)) { try { var files = Directory.GetFiles(domRoot, "*.dll", SearchOption.AllDirectories); foreach (var fileInfo in files.Select(f => new FileInfo(f))) { if (!fileInfo.AlternateDataStreamExists("Zone.Identifier")) { continue; } Log.Information("Removing Zone.Identifier from file {File}", fileInfo.Name); var ads = fileInfo.GetAlternateDataStream("Zone.Identifier", FileMode.Open); ads.Delete(); } } catch (Exception ex) { Log.Fatal("Error unblocking files, program may be unusable, contact support! {@Exception}", ex); Process.Start("https://forums.vigem.org/topic/375/manually-unblock-shibari-archive"); Console.WriteLine("Press any key to escape the madness! :)"); Console.ReadKey(); return; } } else { Log.Information("Process started from {Filesystem} formatted drive, no unblocking necessary", rootDrive.DriveFormat); } #endregion #region Single instance check & hosting // https://stackoverflow.com/a/229567 // get application GUID as defined in AssemblyInfo.cs var appGuid = Guid.Parse("{E7A7AB5E-2C61-4677-9946-427A6B8E0C53}"); // unique id for global mutex - Global prefix means it is global to the machine var mutexId = $"Global\\{{{appGuid}}}"; // Need a place to store a return value in Mutex() constructor call bool createdNew; // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid , null) , MutexRights.FullControl , AccessControlType.Allow ); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(200, false); if (hasHandle == false) { throw new ApplicationException( "This application can only be run once, please check if the service may be running already"); } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, // it will still get acquired hasHandle = true; } HostFactory.Run(x => { x.Service <BusEmulatorHubService>(s => { s.ConstructUsing(name => new BusEmulatorHubService()); s.WhenStarted(tc => tc.Start()); s.WhenStopped(tc => tc.Stop()); }); x.RunAsLocalSystem(); x.SetDescription("Manages AirBender, FireShock & BthPS3 Devices."); x.SetDisplayName("Shibari Dom Server"); x.SetServiceName("Shibari.Dom.Server"); }); } finally { // edited by acidzombie24, added if statement if (hasHandle) { mutex.ReleaseMutex(); } } } #endregion }
private static void Main() { var assembly = Assembly.GetExecutingAssembly(); var fvi = FileVersionInfo.GetVersionInfo(assembly.Location); logger.Info("Application {0}, Version={1} Start", assembly.GetName().Name, fvi.ProductVersion); // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { // edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever // edited by acidzombie24 // mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { logger.Error("Timeout waiting for exclusive access"); throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } // Perform your work here. var p = new Processor(); p.Run(); } finally { // edited by acidzombie24, added if statemnet if (hasHandle) { mutex.ReleaseMutex(); } } } logger.Info("Application {0}, Version={1} End", assembly.GetName().Name, fvi.ProductVersion); }
public static void Main(string[] args) { try { //Allows us to group device runs for logging purposes RunIdentifier = string.Format("{0:yyyy-MM-dd_hh-mm-ss-tt}", DateTime.Now); ParallelProcessObserver = new ProcessObserver(); Trace.Listeners.Add(new TextWriterTraceListener("ParallelDeviceOutput.log", "myListener")); //Get the devices to run for string currentPath = Directory.GetCurrentDirectory(); string baseProjectPath = Path.GetFullPath(Path.Combine(currentPath, @"..\..\..\")); ParameterRetriever retriever = new ParameterRetriever(); PerfectoTestParams testParams = retriever.GetVSOExecParam(baseProjectPath, true); if (testParams.Devices.Count < 0) { Console.WriteLine("No devices found from JSON config file."); #if DEBUG Console.ReadKey(); #endif return; } //Now create a mutex so that this console app can only be run 1 at a time. // get application GUID as defined in AssemblyInfo.cs string appGuid = "PerfectoParallelRunner-82678dc5439649959b6e0b686efb1222"; // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); // Need a place to store a return value in Mutex() constructor call bool createdNew; var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { var hasHandle = false; try { try { hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { throw new TimeoutException("Make sure another Test Process isn't already running."); } } catch (AbandonedMutexException) { // Log the fact that the mutex was abandoned in another process, it will still get acquired hasHandle = true; } // Perform your work here. RunParallelExecutions(testParams); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } } catch (Exception ex) { Console.WriteLine("Error: " + ex.Message); #if DEBUG Console.ReadKey(); #endif throw; } }
private void InternalStart() { try { filesToMove = Directory.GetFiles(buildPath + TEMPORARY_UPDATER_DIRECTORY, "*", SearchOption.AllDirectories).ToList(); int migrationsIndex = filesToMove.FindIndex(f => Path.GetFileName(f) == Migrations.FileName); if (migrationsIndex > -1) { filesToMove.RemoveAt(migrationsIndex); } version = new IniFile(buildPath + TEMPORARY_UPDATER_DIRECTORY + Path.DirectorySeparatorChar + "LocalVersion").GetIntValue("Version", "VersionNumber", version); } catch (DirectoryNotFoundException) { Log("Invalid BuildPath specified in SecondStageUpdaterConfig.ini. " + buildPath + TEMPORARY_UPDATER_DIRECTORY + " is not a valid directory."); Log("Update halted."); Log("Please contact the product developers for support."); return; } Log("Second-Stage Updater"); Log("Written by Rampastring"); Log("http://www.moddb.com/members/rampastring"); Log(""); Log("Waiting for the main application to exit."); if (processCheckMode == ProcessCheckMode.Mutex) { string mutexId = string.Format("Global\\{{{0}}}", appGuid); var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex = new Mutex(false, mutexId, out bool createdNew, securitySettings); while (true) { try { bool hasHandle = mutex.WaitOne(int.MaxValue, false); if (hasHandle) { break; } continue; } catch (AbandonedMutexException) { break; } } } else if (processCheckMode == ProcessCheckMode.ProcessName) { while (true) { Process[] processes = Process.GetProcessesByName(processNameToCheck); if (processes.Length == 0) { break; } foreach (Process process in processes) { process.Dispose(); } Thread.Sleep(1000); } } Thread.Sleep(3000); MoveFiles(); }
public static void LogOffUser() { Mutex mutex = null; bool hasLock = false; try { MutexAccessRule ace = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(ace); mutex = new Mutex(false, "Global\\lithnet.idlelogoff", out bool createdNew, mutexSecurity); mutex.WaitOne(); hasLock = true; ShutdownFlags flags; bool elevated = false; bool isLastSession = false; if (Settings.Action == IdleTimeoutAction.Reboot || Settings.Action == IdleTimeoutAction.Shutdown) { try { NativeMethods.ElevatePrivileges(); elevated = true; } catch (Exception ex) { EventLogging.TryLogEvent($"Could not get workstation shutdown permissions. Logging off instead\n{ex}", EventLogging.EvtRestartfailed, EventLogEntryType.Error); } Process[] p = Process.GetProcessesByName(Process.GetCurrentProcess().ProcessName); isLastSession = p.Length <= 1; if (!isLastSession) { EventLogging.TryLogEvent($"{Settings.Action} will not be performed as other sessions are still active. Logging off instead", EventLogging.EvtSessioninuse, EventLogEntryType.Warning); } } if (isLastSession && elevated && Settings.Action == IdleTimeoutAction.Shutdown) { flags = ShutdownFlags.Shutdown | ShutdownFlags.Force; } else if (isLastSession && elevated && Settings.Action == IdleTimeoutAction.Reboot) { flags = ShutdownFlags.Reboot | ShutdownFlags.Force; } else { flags = ShutdownFlags.Logoff | ShutdownFlags.Force; } if (Settings.Debug) { EventLogging.TryLogEvent($"Performed {flags} for user {Environment.UserName}", 0, EventLogEntryType.Information); } else { if (!NativeMethods.ExitWindowsEx(flags, 0)) { throw new Win32Exception(Marshal.GetLastWin32Error()); } } } finally { if (hasLock) { mutex.ReleaseMutex(); } } }
public void Launch(AddInHost host) { // uncomment to debug #if DEBUG host.MediaCenterEnvironment.Dialog("Attach debugger and hit ok", "debug", DialogButtons.Ok, 100, true); #endif using (Mutex mutex = new Mutex(false, Kernel.MBCLIENT_MUTEX_ID)) { //set up so everyone can access var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); try { //don't bomb if this fails securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); } catch (Exception) { //we don't want to die here and we don't have a logger yet so just go on } try { if (mutex.WaitOne(100, false)) { var config = GetConfig(); if (config == null) { Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } Environment.CurrentDirectory = ApplicationPaths.AppConfigPath; try { CustomResourceManager.SetupStylesMcml(host); CustomResourceManager.SetupFontsMcml(host); } catch (Exception ex) { host.MediaCenterEnvironment.Dialog(ex.Message, Application.CurrentInstance.StringData("CustomErrorDial"), DialogButtons.Ok, 100, true); Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } using (new MediaBrowser.Util.Profiler("Total Kernel Init")) { Kernel.Init(config); } using (new MediaBrowser.Util.Profiler("Application Init")) { Application app = new Application(new MyHistoryOrientedPageSession(), host); app.GoToMenu(); } mutex.ReleaseMutex(); } else { //another instance running and in initialization - just blow out of here Microsoft.MediaCenter.Hosting.AddInHost.Current.ApplicationContext.CloseApplication(); return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get acquired Logger.ReportWarning("Previous instance of core ended abnormally..."); mutex.ReleaseMutex(); } } }
internal static void Main() { //<Snippet2> const string mutexName = "MutexExample4"; Mutex m = null; bool doesNotExist = false; bool unauthorized = false; // The value of this variable is set by the mutex // constructor. It is true if the named system mutex was // created, and false if the named mutex already existed. // bool mutexWasCreated = false; // Attempt to open the named mutex. try { // Open the mutex with (MutexRights.Synchronize | // MutexRights.Modify), to enter and release the // named mutex. // m = Mutex.OpenExisting(mutexName); } catch (WaitHandleCannotBeOpenedException) { Console.WriteLine("Mutex does not exist."); doesNotExist = true; } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); unauthorized = true; } //</Snippet2> // There are three cases: (1) The mutex does not exist. // (2) The mutex exists, but the current user doesn't // have access. (3) The mutex exists and the user has // access. // if (doesNotExist) { //<Snippet4> // The mutex does not exist, so create it. // Create an access control list (ACL) that denies the // current user the right to enter or release the // mutex, but allows the right to read and change // security information for the mutex. // string user = Environment.UserDomainName + "\\" + Environment.UserName; MutexSecurity mSec = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Deny); mSec.AddAccessRule(rule); rule = new MutexAccessRule(user, MutexRights.ReadPermissions | MutexRights.ChangePermissions, AccessControlType.Allow); mSec.AddAccessRule(rule); // Create a Mutex object that represents the system // mutex named by the constant 'mutexName', with // initial ownership for this thread, and with the // specified security access. The Boolean value that // indicates creation of the underlying system object // is placed in mutexWasCreated. // m = new Mutex(true, mutexName, out mutexWasCreated, mSec); // If the named system mutex was created, it can be // used by the current instance of this program, even // though the current user is denied access. The current // program owns the mutex. Otherwise, exit the program. // if (mutexWasCreated) { Console.WriteLine("Created the mutex."); } else { Console.WriteLine("Unable to create the mutex."); return; } //</Snippet4> } else if (unauthorized) { //<Snippet3> // Open the mutex to read and change the access control // security. The access control security defined above // allows the current user to do this. // try { m = Mutex.OpenExisting(mutexName, MutexRights.ReadPermissions | MutexRights.ChangePermissions); // Get the current ACL. This requires // MutexRights.ReadPermissions. MutexSecurity mSec = m.GetAccessControl(); string user = Environment.UserDomainName + "\\" + Environment.UserName; // First, the rule that denied the current user // the right to enter and release the mutex must // be removed. MutexAccessRule rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Deny); mSec.RemoveAccessRule(rule); // Now grant the user the correct rights. // rule = new MutexAccessRule(user, MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); mSec.AddAccessRule(rule); // Update the ACL. This requires // MutexRights.ChangePermissions. m.SetAccessControl(mSec); Console.WriteLine("Updated mutex security."); // Open the mutex with (MutexRights.Synchronize // | MutexRights.Modify), the rights required to // enter and release the mutex. // m = Mutex.OpenExisting(mutexName); //</Snippet3> } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unable to change permissions: {0}", ex.Message); return; } } // If this program created the mutex, it already owns // the mutex. // if (!mutexWasCreated) { // Enter the mutex, and hold it until the program // exits. // try { Console.WriteLine("Wait for the mutex."); m.WaitOne(); Console.WriteLine("Entered the mutex."); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); } } Console.WriteLine("Press the Enter key to exit."); Console.ReadLine(); m.ReleaseMutex(); m.Dispose(); }
static LogHelper() { var assembly = Assembly.GetCallingAssembly().GetName(); string appVersion = assembly.Version.ToString(); string assemblyName = assembly.Name; CurrentLogsPath = AppDomain.CurrentDomain.BaseDirectory; logFilePath = Path.Combine(CurrentLogsPath, assemblyName + ".log"); MutexSecurity logFileMutexSecurity = new MutexSecurity(); MutexAccessRule rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.Synchronize | MutexRights.Modify, AccessControlType.Allow); logFileMutexSecurity.AddAccessRule(rule); rule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.ChangePermissions | MutexRights.TakeOwnership, AccessControlType.Deny); logFileMutexSecurity.AddAccessRule(rule); logFileMutex = new Mutex(false, "Global\\" + logFileMutexName, out bool createdNew, logFileMutexSecurity); //Note: We don't use createdNew bool LoggingFailed = false; try { logFileMutex.WaitOne(); } catch (AbandonedMutexException /*ex*/) { //Mutex was abandoned; previous instance probably crashed while holding it. //Console.WriteLine("Exception on return from WaitOne." + "\r\n\tMessage: {0}", ex.Message); } try { //Every once in a while, some external program holds on to our logfile (probably anti-virus suites). So we have a retry-structure here. uint RetryCount = 0; while (true) { try { using (var fs = new FileStream(logFilePath, FileMode.Append, FileAccess.Write, FileShare.Read)) { if (!fs.CanWrite) { CurrentLogsPath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "Wokhan Solutions", "WFN"); logFilePath = Path.Combine(CurrentLogsPath, assemblyName + ".log"); } } break; } catch (IOException) { if (RetryCount == Retries) { LoggingFailed = true; //Let's release the Mutex before showing the messagebox. //throw would create an endless loop, so let's just ignore all of this mess... break; } RetryCount++; Thread.Sleep(RetryDelay); } } } finally { logFileMutex.ReleaseMutex(); } if (LoggingFailed) { if (!WindowsIdentity.GetCurrent().IsSystem) //Don't try to display a messagebox when we're SYSTEM, as this is not allowed. { MessageBox.Show(Resources.MSG_LOG_FAILED, Resources.MSG_DLG_ERR_TITLE, MessageBoxButton.OK, MessageBoxImage.Error); } } if (Settings.Default.FirstRun) { writeLog("INIT", String.Format("OS: {0} ({1} bit) / .Net CLR: {2} / Path: {3} / Version: {4} ({5} bit)", Environment.OSVersion, Environment.Is64BitOperatingSystem ? 64 : 32, Environment.Version, AppDomain.CurrentDomain.BaseDirectory, appVersion, Environment.Is64BitProcess ? 64 : 32)); } }
/// <summary> /// it's a good idea to put all the low level communication with the device here - then all communication calls this function. /// </summary> /// <param name="command">given command</param> /// <param name="raw">if true, skip formatting. If false, format command text</param> /// <param name="async">if true, do not wait for response</param> /// <returns>response text, in case of empty command or async empty string</returns> private string CommandString(string command, bool raw, bool async) { //init if (serialMutex == null) { //set up security for multi-user usage + add support for localized systems (don't use just "Everyone") MutexAccessRule allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); MutexSecurity securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); serialMutex = new Mutex(false, driverID, out createdNew, securitySettings); } var response = string.Empty; //if command is empty, return immediately if (string.IsNullOrWhiteSpace(command)) { return(response); } //format command if not raw if (!raw) { command = Helper.FormatCommand(command); } try { try { //mutex lock to ensure that only one command is in progress at a time (http://www.ascom-standards.org/Help/Developer/html/caf6b21d-755a-4f1c-891f-ce971a9a2f79.htm) //note, we want to time out here instead of waiting forever hasHandle = serialMutex.WaitOne(commandTimeout, false); if (hasHandle == false) { throw new TimeoutException("Timeout waiting for exclusive access"); } //tl.LogMessage("CommandString mutex", "mutex acquired"); } catch (AbandonedMutexException) { //log the fact that the mutex was abandoned in another process, it will still get acquired //tl.LogMessage("CommandString mutex", "mutex acquired via abandon"); hasHandle = true; } //serial communication var watch = Stopwatch.StartNew(); if (async) { tl.LogMessage("CommandString async", string.Format("Sending command {0}", command)); tls.LogMessage("Request async", command); serial.ClearBuffers(); serial.Transmit(command); //async message - do not wait for response } else { tls.LogMessage("Request", command); serial.ClearBuffers(); serial.Transmit(command); response = serial.ReceiveTerminated(")"); //wait until termination character if (response.StartsWith("!")) { throw new ApplicationException($"Command failed, response: {response}"); } tls.LogMessage("Response", response); tl.LogMessage("CommandString sync", $"Response for {command} received: {response}"); response = response.TrimStart('(').TrimEnd(')'); } //maximum frequency is XYHz so execution must take at least XYms //watch.Stop(); //if (watch.ElapsedMilliseconds < commandTimeoutMs) //utilities.WaitForMilliseconds((int)(commandTimeoutMs - watch.ElapsedMilliseconds)); } catch (Exception e) { tl.LogMessage("CommandString error", $"Command: {command}, Message: {e.Message}, StackTrace: {e.StackTrace}"); throw; } finally { if (hasHandle) { serialMutex.ReleaseMutex(); //tl.LogMessage("CommandString mutex", "mutex released"); } } return(response); }
static void Main(string[] args) { /* * if (System.DateTime.Compare(DateTime.Now, new DateTime(MuteFm.Constants.ExpireYear, MuteFm.Constants.ExpireMonth, MuteFm.Constants.ExpireDay, 23, 59, 59, DateTimeKind.Utc)) > 0) * { * MessageBox.Show("This version of mute.fm is beta software and has expired. Thanks for demoing! Get a new version at http://www.mutefm.com/"); * return; * }*/ MuteFm.SmartVolManagerPackage.SoundEventLogger.LogMsg(Constants.ProgramName + " loaded!"); if (System.Environment.CommandLine.ToUpper().Contains("FIRSTTIME")) { FirstTime = true; } if (System.Environment.CommandLine.ToUpper().Contains("SERVICE")) { IsService = true; } if ((args.Length > 0) && (args[0].ToUpper().Contains("INTERNALBUILDMODE"))) { InternalBuildMode = true; } // Initialize Awesomium (the browser control) /* if (Awesomium.Core.WebCore.IsChildProcess) * { * Awesomium.Core.WebCore.ChildProcessMain(); * return; * }*/ #if !NOAWE Awesomium.Core.WebConfig config = new Awesomium.Core.WebConfig(); // config.UserAgent = "Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/30.0.1599.17 Safari/537.36"; //TODO-AWE config.EnableDatabases = true; //TODO-AWE config.SaveCacheAndCookies = true; //config.LogLevel = Awesomium.Core.LogLevel.Verbose; #if !DEBUG config.LogLevel = Awesomium.Core.LogLevel.None; #else config.LogLevel = Awesomium.Core.LogLevel.Normal; #endif if (!InternalBuildMode) { string path = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location); config.ChildProcessPath = path + "/mute_fm_web"; //TODO-AWE config.ChildProcessPath = Awesomium.Core.WebConfig.CHILD_PROCESS_SELF; } Awesomium.Core.WebCore.Initialize(config); #endif // get application GUID as defined in AssemblyInfo.cs string appGuid = ((GuidAttribute)System.Reflection.Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine string mutexId = string.Format("Global\\{{{0}}}", appGuid); using (var mutex = new Mutex(false, mutexId)) { // note: some of this is Windows-only // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); //edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever //edited by acidzombie24 //mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(500, false); // was 5000 here // We just show a UI here if (hasHandle == false) { //MessageBox. Show(Constants.ProgramName + " is already running. You can access it via the system tray."); MuteFm.UiPackage.PlayerForm playerForm = new UiPackage.PlayerForm(); playerForm.Show(); playerForm.Init(true); Application.Run(playerForm); Environment.Exit(0); //MessageBox. Show(Constants.ProgramName + " is already running. You can access it via the system tray or the " + Constants.ProgramName + " Google Chrome extension."); //Environment.Exit(1); //throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired hasHandle = true; } // Perform your work here. Init(args); } finally { //edit by acidzombie24, added if statemnet if (hasHandle) { mutex.ReleaseMutex(); } } //SmartVolManagerPackage.SoundServer.RestoreVolumes(); Environment.Exit(0); } }
public static void Open() { // no implementation for unix systems if (Software.OperatingSystem.IsUnix) { return; } if (_driver != null) { return; } // clear the current report _report.Length = 0; _driver = new KernelDriver("WinRing0_1_2_0"); _driver.Open(); if (!_driver.IsOpen) { // driver is not loaded, try to install and open _fileName = GetTempFileName(); if (_fileName != null && ExtractDriver(_fileName)) { if (_driver.Install(_fileName, out string installError)) { _driver.Open(); if (!_driver.IsOpen) { _driver.Delete(); _report.AppendLine("Status: Opening driver failed after install"); } } else { string errorFirstInstall = installError; // install failed, try to delete and reinstall _driver.Delete(); // wait a short moment to give the OS a chance to remove the driver Thread.Sleep(2000); if (_driver.Install(_fileName, out string errorSecondInstall)) { _driver.Open(); if (!_driver.IsOpen) { _driver.Delete(); _report.AppendLine("Status: Opening driver failed after reinstall"); } } else { _report.AppendLine("Status: Installing driver \"" + _fileName + "\" failed" + (File.Exists(_fileName) ? " and file exists" : string.Empty)); _report.AppendLine("First Exception: " + errorFirstInstall); _report.AppendLine("Second Exception: " + errorSecondInstall); } } } else { _report.AppendLine("Status: Extracting driver failed"); } try { // try to delete the driver file if (File.Exists(_fileName) && _fileName != null) { File.Delete(_fileName); } _fileName = null; } catch (IOException) { } catch (UnauthorizedAccessException) { } } if (!_driver.IsOpen) { _driver = null; } const string isaMutexName = "Global\\Access_ISABUS.HTP.Method"; try { #if NETFRAMEWORK //mutex permissions set to everyone to allow other software to access the hardware //otherwise other monitoring software cant access var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); _isaBusMutex = new Mutex(false, isaMutexName, out _, securitySettings); #else _isaBusMutex = new Mutex(false, isaMutexName); #endif } catch (UnauthorizedAccessException) { try { #if NETFRAMEWORK _isaBusMutex = Mutex.OpenExisting(isaMutexName, MutexRights.Synchronize); #else _isaBusMutex = Mutex.OpenExisting(isaMutexName); #endif } catch { } } const string pciMutexName = "Global\\Access_PCI"; try { _pciBusMutex = new Mutex(false, pciMutexName); } catch (UnauthorizedAccessException) { try { #if NETFRAMEWORK _pciBusMutex = Mutex.OpenExisting(pciMutexName, MutexRights.Synchronize); #else _pciBusMutex = Mutex.OpenExisting(pciMutexName); #endif } catch { } } }
private static void Main() { // prevent running if launcher is up if (Process.GetProcesses() .Any( proc => string.CompareOrdinal(proc.ProcessName, Resources.Launcher) == 0)) { Logger.Write("обнаружен запущенный лончер, не работаю."); return; } // prevent multiple instances // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 // get application GUID as defined in AssemblyInfo.cs var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly(). GetCustomAttributes(typeof(GuidAttribute), false). GetValue(0)).Value; // unique id for global mutex - Global prefix means it is global to the machine var mutexId = $"Global\\{{{appGuid}}}"; // Need a place to store a return value in Mutex() constructor call bool createdNew; var allowEveryoneRule = new MutexAccessRule( new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings)) { var hasHandle = false; try { try { hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { throw new TimeoutException("Timeout waiting for exclusive access"); } } catch (AbandonedMutexException) { Logger.Write("Mutex was abandoned in another process."); hasHandle = true; } Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(false); Application.Run(new FormUpdater()); } finally { if (hasHandle) { mutex.ReleaseMutex(); } } } }
public bool RemoveAccessRule(MutexAccessRule rule);
static void Main() { Application.EnableVisualStyles(); Application.SetCompatibleTextRenderingDefault(true); string title = "KeyMagic"; bool beta = Properties.Settings.Default.BetaRelease; if (beta) { title += " (beta)"; } string mutexName = "\u1000\u1001"; // http://stackoverflow.com/questions/229565/what-is-a-good-pattern-for-using-a-global-mutex-in-c/229567 using (var mutex = new Mutex(false, mutexName)) { // edited by Jeremy Wiebe to add example of setting up security for multi-user usage // edited by 'Marc' to work also on localized systems (don't use just "Everyone") var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); mutex.SetAccessControl(securitySettings); //edited by acidzombie24 var hasHandle = false; try { try { // note, you may want to time out here instead of waiting forever //edited by acidzombie24 //mutex.WaitOne(Timeout.Infinite, false); hasHandle = mutex.WaitOne(100, false); if (hasHandle == false) //another instance exist { IntPtr pWnd = NativeMethods.FindWindow(null, title); if (pWnd != IntPtr.Zero) { NativeMethods.ShowWindow(pWnd, 0x05); } return; } } catch (AbandonedMutexException) { // Log the fact the mutex was abandoned in another process, it will still get aquired } frmMain f = new frmMain(); Application.Run(); } finally { //edit by acidzombie24, added if statemnet if (hasHandle) { mutex.ReleaseMutex(); } } } }
public void RemoveAccessRuleSpecific(MutexAccessRule rule);
private void StartGlobalHookLogger(string type, Action <string, FileStream> loggerAction) { while (true) { try { bool createdNew; var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var mutexSecurity = new MutexSecurity(); mutexSecurity.AddAccessRule(allowEveryoneRule); // Need to add user to: Computer Configuration\Windows Settings\Security Settings\Local Policies\User Rights Assignment\Create global objects // to be able to create global objects, also need to reboot or logon again // To apply the setting: secedit /configure /db secedit.sdb /cfg "suncatprivs.inf" /overwrite /quiet using (var mutex = new Mutex(false, $@"Global\Suncat{type}HookMapMutex", out createdNew, mutexSecurity)) { var mapName = $"Suncat{type}HookMap"; var dataDir = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "SuncatSvc", "Hook"); Directory.CreateDirectory(dataDir); while (mutex.WaitOne()) { try { using (var fileStream = new FileStream($@"{dataDir}\{mapName}.data", FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite)) { loggerAction(type, fileStream); } } catch (Exception ex) { #if DEBUG Debug.WriteLine(ex); if (ex.InnerException != null) { Debug.WriteLine(ex.InnerException); } #else Trace.WriteLine(ex); if (ex.InnerException != null) { Trace.WriteLine(ex.InnerException); } #endif break; } finally { mutex.ReleaseMutex(); } Thread.Sleep(500); } } } catch (Exception ex) { #if DEBUG Debug.WriteLine(ex); if (ex.InnerException != null) { Debug.WriteLine(ex.InnerException); } #else Trace.WriteLine(ex); if (ex.InnerException != null) { Trace.WriteLine(ex.InnerException); } #endif } Thread.Sleep(500); } }
public void SetAccessRule(MutexAccessRule rule);
static int Main() { // get application GUID as defined in AssemblyInfo.cs var appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString(); // unique id for global mutex - Global prefix means it is global to the machine var mutexId = string.Format("Global\\{{{0}}}", appGuid); var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow); var securitySettings = new MutexSecurity(); securitySettings.AddAccessRule(allowEveryoneRule); // edited by MasonGZhwiti to prevent race condition on security settings via VanNguyen var mutex = new Mutex(false, mutexId, out bool createdNew, securitySettings); if (!createdNew) { var setVals = ParseRegValues(); if (!setVals) { return(0); } // Create the channel. IpcChannel channel = new IpcChannel(); // Register the channel. ChannelServices.RegisterChannel(channel, false); // Register as client for remote object. WellKnownClientTypeEntry remoteType = new WellKnownClientTypeEntry(typeof(VarSetter), "ipc://localhost:1337/SRUserInfo.rem"); RemotingConfiguration.RegisterWellKnownClientType(remoteType); // Create a message sink. IMessageSink messageSink = channel.CreateMessageSink("ipc://localhost:1337/SRUserInfo.rem", null, out string objectUri); // Create an instance of the remote object. VarSetter service = new VarSetter(); service.setVars(UserName, ExerciseId); return(0); } var hasHandle = false; try { try { hasHandle = mutex.WaitOne(5000, false); if (hasHandle == false) { throw new TimeoutException(); } } catch (AbandonedMutexException) { // the mutex was abandoned in another process, // it will still get acquired hasHandle = true; } var setVals = ParseRegValues(); if (!setVals) { return(0); } OpenIPCAsync(); Run(); } finally { if (hasHandle) { mutex.ReleaseMutex(); mutex.Dispose(); } } return(0); }