/////////////////////////////////////////////////////////////////////// public static EventWaitHandle OpenEvent( string name ) { EventWaitHandle @event = null; try { @event = EventWaitHandle.OpenExisting(name); } catch (Exception e) { TraceOps.DebugTrace( e, typeof(ThreadOps).Name, TracePriority.HandleError); } #if DEBUG && VERBOSE TraceOps.DebugTrace(String.Format( "OpenEvent: {0}, name = {1}", (@event != null) ? "success" : "failure", FormatOps.WrapOrNull(name)), typeof(ThreadOps).Name, TracePriority.EventDebug); #endif return(@event); }
private static bool SignalProcDumpDetach(int targetPid) { string ewhName = "Procdump-" + targetPid.ToString(); EventWaitHandle ewh = null; // Attempt to open and signal the named event to shut down the debugger Ex: Procdump-5555 try { ewh = EventWaitHandle.OpenExisting(ewhName); ewh.Set(); Console.WriteLine("Named event " + ewhName + " signaled"); } catch (WaitHandleCannotBeOpenedException) { Console.WriteLine("Named event " + ewhName + " does not exist."); return(false); } catch (UnauthorizedAccessException ex) { Console.WriteLine("Unauthorized access: {0}", ex.Message); return(false); } //if we didn't catch anything assume success or target process exited return(true); }
public static void MakeSingleInstance(string name, ISingleInstance app) { EventWaitHandle eventWaitHandle = null; var isFirstInstance = false; var eventName = Environment.MachineName + "-" + name; try { eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // it's the first instance isFirstInstance = true; } if (isFirstInstance) { eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName); ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, _OnWaitOrTimerCallback, app, Timeout.Infinite, false); // not need anymore eventWaitHandle.Close(); } else { // inform the first instance, that a new instanc has tried to start. eventWaitHandle.Set(); Environment.Exit(0); } }
public static void Run(int port, ITrace trace) { File.Delete("RemoteHost.txt"); using (TestOutputFile = new StreamWriter( File.Open("RemoteHost.txt", FileMode.CreateNew, FileAccess.ReadWrite, FileShare.None))) { var serializer = new Serializer <ISerializableMessage>(); serializer.AddType <TestData>(); serializer.AddType <TestControl>(); var serverConfiguration = new ServerConfiguration(port); var server = new Net.Server(serverConfiguration, trace); Console.WriteLine("Starting server"); server.NewServerPeer += (server1, serverPeer) => { serverPeer.NewConnection += (serverPeer1, connection) => new ServerConnection(serializer, trace).Server_NewConnection(server1, connection); }; server.StartReceiving(); Console.WriteLine("Setting signal that we are up and running"); using (var startEvent = EventWaitHandle.OpenExisting("testRemoteServer")) { startEvent.Set(); } Console.WriteLine("Waiting for stop events"); StopEvent.WaitOne(600000); server.Dispose(); } }
public void OpenExisting_Windows() { string name = Guid.NewGuid().ToString("N"); EventWaitHandle resultHandle; Assert.False(EventWaitHandle.TryOpenExisting(name, out resultHandle)); Assert.Null(resultHandle); using (EventWaitHandle are1 = new EventWaitHandle(false, EventResetMode.AutoReset, name)) { using (EventWaitHandle are2 = EventWaitHandle.OpenExisting(name)) { are1.Set(); Assert.True(are2.WaitOne(0)); Assert.False(are1.WaitOne(0)); Assert.False(are2.WaitOne(0)); are2.Set(); Assert.True(are1.WaitOne(0)); Assert.False(are2.WaitOne(0)); Assert.False(are1.WaitOne(0)); } Assert.True(EventWaitHandle.TryOpenExisting(name, out resultHandle)); Assert.NotNull(resultHandle); resultHandle.Dispose(); } }
private static void SignalReady(string id) { using (EventWaitHandle signal = EventWaitHandle.OpenExisting(id)) { signal.Set(); } }
[STAThread] // This is needed for WPF apps, not sure about other //TODO: would there be a case where MTA is needed? //"they must protect their internal state against concurrent calls, in case they're loaded in the MTA, but must not block, in case they're loaded in an STA." //http://stackoverflow.com/a/127340/66372 //"If you're only going to consume COM components all that you really need to know is that you have to match the apartment to the component or nasty things will happen." //http://stackoverflow.com/a/485109/66372 static void Main(string[] args) { string OSBOXPARAMS = Environment.GetEnvironmentVariable("OSBOXPARAMS"); int delimPos = OSBOXPARAMS.IndexOf(" "); //TODO: could an access violation exception be coming from .OpenExisting - http://msdn.microsoft.com/en-US/library/530zssyk(v=VS.80).aspx // i.e. "If you run the compiled example from two command windows, the second copy will throw an access violation exception on the call to OpenExisting(String)." EventWaitHandle injectionDone = EventWaitHandle.OpenExisting(OSBOXPARAMS.Substring(0, delimPos)); string assemblyPath = OSBOXPARAMS.Substring(delimPos + 2, OSBOXPARAMS.Length - delimPos - 3); // assumming path is quoted // Waiting until injection is done injectionDone.WaitOne(); AppDomainSetup ads = new AppDomainSetup(); ads.ApplicationBase = System.Environment.CurrentDirectory; ads.ConfigurationFile = assemblyPath + ".config"; AppDomain ad2 = AppDomain.CreateDomain("AD #2", null, ads); // Assembly title = Assembly.LoadFile(assemblyPath); // Removing first item from the list of arguments // args = args.Where((val, idx) => idx > 1).ToArray(); // System.Windows.Forms.MessageBox.Show("before"); ad2.ExecuteAssembly(assemblyPath, args); AppDomain.Unload(ad2); /* object[] parameters = new object[0]; * if (title.EntryPoint.GetParameters().Length > 0) * { * parameters = new object[] { args }; * } * title.EntryPoint.Invoke(null, parameters); */ }
private void SignalReady() { var eventName = _name + ".Ready"; var readyEvent = EventWaitHandle.OpenExisting(eventName); readyEvent.Set(); }
public static SharedMemoryIPC Connect(string sharedMemoryIPCName, FileMapAccess fileMapAccess) { SharedMemory sharedMemory = Open(sharedMemoryIPCName, fileMapAccess); EventWaitHandle serverEvent; EventWaitHandle clientEvent; string serverEventName = sharedMemory.ReadString(0); try { serverEvent = EventWaitHandle.OpenExisting(serverEventName); clientEvent = EventWaitHandle.OpenExisting(sharedMemory.ReadString(serverEventName.Length + 1)); } catch (Win32Exception ex) { if (ex.ErrorCode == 0x000010d8) { throw new NoServerException(); } else { throw; } } clientEvent.Set(); return(new SharedMemoryIPC(sharedMemory, serverEvent, clientEvent)); }
protected override void OnStart(string[] args) { // okay, the 'args' here are ONLY for when the service is started via the Properties dialog in services.msc try { using (TokenHandle my_token = TokenUtil.OpenProcessToken(Process.GetCurrentProcess(), TokenAccess.TOKEN_ADJUST_PRIVILEGES | TokenAccess.TOKEN_DUPLICATE)) { PrivilegeState[] privs = new PrivilegeState[] { new PrivilegeState(TokenPrivileges.SE_TCB_NAME, true) }; if (!my_token.AdjustPrivileges(privs)) { throw new Win32Exception(); } // open the token of the process that lives in the session we want Process proc = Process.GetProcessById(this.Pid); TokenHandle proc_token = TokenUtil.OpenProcessToken(proc.Handle, TokenAccess.TOKEN_READ); // create a primary token TokenHandle new_token = TokenUtil.DuplicateTokenEx(my_token, TokenAccess.TOKEN_ALL_ACCESS, SECURITY_IMPERSONATION_LEVEL.SecurityDelegation, TOKEN_TYPE.TokenPrimary); // override the session under which it's going to be created new_token.SessionId = proc_token.SessionId; string cmd_exe = Environment.GetEnvironmentVariable("COMSPEC"); STARTUPINFO sui = new STARTUPINFO(); sui.cb = Marshal.SizeOf(typeof(STARTUPINFO)); PROCESS_INFORMATION procinfo; bool result = Advapi32.CreateProcessAsUser( new_token, cmd_exe, cmd_exe, IntPtr.Zero, // default process attributes IntPtr.Zero, // default thread attributes false, CreateProcessFlags.CREATE_NEW_CONSOLE | CreateProcessFlags.CREATE_NEW_PROCESS_GROUP | CreateProcessFlags.CREATE_DEFAULT_ERROR_MODE | CreateProcessFlags.CREATE_BREAKAWAY_FROM_JOB | CreateProcessFlags.CREATE_PRESERVE_CODE_AUTHZ_LEVEL | CreateProcessFlags.CREATE_UNICODE_ENVIRONMENT, IntPtr.Zero, // inherit environment null, // inherit current directory ref sui, out procinfo); if (!result) { throw new Win32Exception(); } } } catch { this.ExitCode = 1; } finally { EventWaitHandle ewh = EventWaitHandle.OpenExisting(EventName); ewh.Set(); } ThreadPool.QueueUserWorkItem(DoStop); }
private void Application_Startup(object sender, StartupEventArgs e) { bool created; waitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, WaitHandleName, out created); if (created) { CultureInfo info = new CultureInfo("ru-Ru"); Thread.CurrentThread.CurrentCulture = info; Thread.CurrentThread.CurrentUICulture = info; var mainWindow = new MainWindow { DataContext = new MainWindowViewModel() }; mainWindow.Closed += (sender, e) => { Application.Current.Shutdown(); }; mainWindow.Show(); } else { try { waitHandle = EventWaitHandle.OpenExisting(WaitHandleName); waitHandle.Set(); } finally { Shutdown(); } } }
private void GetConnectNumber(uint timeOut) { EventWaitHandle eventWaitHandle; try { eventWaitHandle = EventWaitHandle.OpenExisting(this.memoryName + "_CONNECT_REQUEST"); } catch (Exception) { string str = "Global\\" + this.memoryName; eventWaitHandle = EventWaitHandle.OpenExisting(str + "_CONNECT_REQUEST"); this.memoryName = str; } EventWaitHandle eventWaitHandle2 = EventWaitHandle.OpenExisting(this.memoryName + "_CONNECT_ANSWER"); using (SharedMemory sharedMemory = new SharedMemory(this.memoryName + "_CONNECT_DATA", (IntPtr)4)) { if (!eventWaitHandle.Set()) { throw new MySqlException("Failed to open shared memory connection"); } if (!eventWaitHandle2.WaitOne((int)(timeOut * 1000u), false)) { throw new MySqlException("Timeout during connection"); } this.connectNumber = Marshal.ReadInt32(sharedMemory.View); } }
public void StartThreadStressScenario() { var expectedWaitHandle = $"thread_profile_stress_begin_{Port}"; var remoteAppEvent = EventWaitHandle.OpenExisting(expectedWaitHandle); remoteAppEvent.Set(); }
private void InitFields() { try { _RxlDataSet = new RxlDataSet(); _SingleLock = new Dictionary <string, EventWaitHandle>(); foreach (DataTable table in _RxlDataSet.Tables) { bool createdNew = false; string handleName = string.Format("{0}{1}Lock", DefaultApplicationInfo.AbbreviatedApplicationName, table.TableName); EventWaitHandle waitHandle = null; try { waitHandle = EventWaitHandle.OpenExisting(handleName, EventWaitHandleRights.FullControl); } catch { } if (waitHandle == null) { EventWaitHandleSecurity waitHandleSecurity = new EventWaitHandleSecurity(); waitHandleSecurity.SetAccessRule(new EventWaitHandleAccessRule(@"BUILTIN\Administrators", EventWaitHandleRights.FullControl, AccessControlType.Allow)); waitHandle = new EventWaitHandle(true, EventResetMode.AutoReset, handleName, out createdNew, waitHandleSecurity); } _SingleLock.Add(table.TableName, waitHandle); } } catch { throw; } }
public static bool CreateSingleInstance(string name, EventHandler <InstanceCallbackEventArgs> callback, string[] args) { string eventName = string.Format("{0}-{1}", Environment.MachineName, name); InstanceProxy.IsFirstInstance = false; InstanceProxy.CommandLineArgs = args; try { using (EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(eventName)) { UpdateRemoteObject(name); if (eventWaitHandle != null) { eventWaitHandle.Set(); } } Environment.Exit(0); } catch { InstanceProxy.IsFirstInstance = true; using (EventWaitHandle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName)) { ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, callback, Timeout.Infinite, false); } RegisterRemoteType(name); } return(InstanceProxy.IsFirstInstance); }
/// <summary> /// Target applications should call this method to notify the AppMonitor that it should shutdown the application /// </summary> public static void NotifyStopMonitoring() { GlobalLog.LogStatus("Notifying ApplicationMonitor to stop monitoring"); if (abortSignal == null) { GlobalLog.LogStatus("Abort signal not available, trying to find existing wait handle by name..."); try { abortSignal = EventWaitHandle.OpenExisting("ApplicationMonitorAbortSignal"); } catch (WaitHandleCannotBeOpenedException) { GlobalLog.LogStatus("Abort signal did not exist, so cross-proc NotifyStopMonitoring may fail."); } } if (abortSignal != null) { abortSignal.Set(); GlobalLog.LogStatus("Abort signal set."); } else { GlobalLog.LogStatus("WARNING: Could not get Abort Signal to use!"); } }
internal static void Make(SingleInstanceMode singleInstanceModes) { var appName = Application.Current.GetType().Assembly.ManifestModule.ScopeName; var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent(); var keyUserName = windowsIdentity != null?windowsIdentity.User.ToString() : string.Empty; // Be careful! Max 260 chars! var eventWaitHandleName = string.Format("{0}{1}", appName, singleInstanceModes == SingleInstanceMode.ForEveryUser ? keyUserName : string.Empty); try { using (var eventWaitHandle = EventWaitHandle.OpenExisting(eventWaitHandleName)) { // It informs first instance about other startup attempting. eventWaitHandle.Set(); } Environment.Exit(0); } catch { // It's first instance. // Register EventWaitHandle. using (var eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventWaitHandleName)) { ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, OtherInstanceAttemptedToStart, null, Timeout.Infinite, false); } RemoveApplicationsStartupDeadlockForStartupCrushedWindows(); } }
private void CreateMultipleInstance(string[] args) { try { InstanceProxy.CommandLineArgs = args; using (EventWaitHandle eventWaitHandle = EventWaitHandle.OpenExisting(EventName)) { semaphore = Semaphore.OpenExisting(SemaphoreName); semaphore.WaitOne(); UpdateRemoteObject(AppName); if (eventWaitHandle != null) { eventWaitHandle.Set(); } } } catch (Exception e) { DebugHelper.WriteException(e); } Environment.Exit(0); }
private static bool SignalTermination() { var diadocProcesses = GetCoreWarProcesses(); foreach (var process in diadocProcesses) { var eventName = string.Format("Global\\{0}", process.ProcessName); try { using (var stopSignal = EventWaitHandle.OpenExisting(eventName, EventWaitHandleRights.Modify)) stopSignal.Set(); Console.Out.WriteLine("Event signaled: {0}", eventName); } catch (UnauthorizedAccessException e) { Console.Out.WriteLine("Event not signaled: {0}. Exception: {1}", eventName, e); } catch (IOException e) { Console.Out.WriteLine("Event not signaled: {0}. Exception: {1}", eventName, e); } catch (WaitHandleCannotBeOpenedException e) { Console.Out.WriteLine("Event not signaled: {0}. Exception: {1}", eventName, e); } } return(diadocProcesses.Any()); }
public void OpenExisting_NotSupported_Unix() { Assert.Throws <PlatformNotSupportedException>(() => EventWaitHandle.OpenExisting("anything")); EventWaitHandle ewh; Assert.Throws <PlatformNotSupportedException>(() => EventWaitHandle.TryOpenExisting("anything", out ewh)); }
private static bool InstanceAlreadyExists() { try { // Checking for another instance of the application... // Open if another instance is already running. It throws if there's none m_ThreadComEvent = EventWaitHandle.OpenExisting(m_SingleAppComEventName); // Signal that main instance m_ThreadComEvent.Set(); m_ThreadComEvent.Close(); // Start the Named Pipe server so that the cmdline parameters // of this instance can be passed to the main instance. // The main instance, once signalled, will initiate the chat with this instance StartNamedPipeServer(); return(true); } catch (WaitHandleCannotBeOpenedException ex) { // Expected: No other instance of the application was detected } catch (Exception ex) { // Unexpected: Assume no other instance anyway. // Log or do something with this } return(false); }
private static bool HaveOtherInstance() { try { EventWaitHandle globalHandler = EventWaitHandle.OpenExisting("HaveOne"); globalHandler.Set(); return(true); } catch (WaitHandleCannotBeOpenedException) { EventWaitHandle global = new EventWaitHandle(true, EventResetMode.AutoReset, "HaveOne"); Thread monitor = new Thread(new ThreadStart(delegate() { while (true) { global.WaitOne(); //MessageBox.Show("I'm here bbb..."); Form form = Core.CoreData[CoreDataType.ApplicationForm] as Form; if (form != null) { // form.BeginInvoke(new ThreadStart(form.Show)); form.WindowState = FormWindowState.Maximized; } } })); monitor.IsBackground = true; monitor.Start(); GC.KeepAlive(monitor); return(false); } }
/// <summary> /// Creates the single instance. /// </summary> /// <param name="name">The name.</param> /// <returns></returns> public static bool IsFirstInstance(string name) { EventWaitHandle eventWaitHandle = null; string eventName = string.Format("{0}-{1}", Environment.MachineName, name); var isFirstInstance = false; try { // try opening existing wait handle eventWaitHandle = EventWaitHandle.OpenExisting(eventName); } catch { // got exception = handle wasn't created yet isFirstInstance = true; } if (isFirstInstance) { // init handle eventWaitHandle = new EventWaitHandle(false, EventResetMode.AutoReset, eventName); // register wait handle for this instance (process) ThreadPool.RegisterWaitForSingleObject(eventWaitHandle, WaitOrTimerCallback, null, Timeout.Infinite, false); eventWaitHandle.Close(); } return(isFirstInstance); }
static void Main(string[] args) { //Try get a handle to the event Console.WriteLine("==== Software Update Service Command Line Management Tool ===="); Console.WriteLine(" ==== by Serious Information Security Inc. ===="); Console.WriteLine("Attempting to trigger a check for software updates by the service"); Console.WriteLine("Opening global update trigger"); EventWaitHandle ewh; try { ewh = EventWaitHandle.OpenExisting(TRIGGER_EVENT_NAME); } catch (Exception e) { Console.WriteLine("ERROR: Unable to open update trigger event. Try restarting this VM, if it continues contact EXCON"); Console.WriteLine(e.ToString()); return; } Console.WriteLine("Triggering an update check"); try { ewh.Set(); ewh.Close(); Console.WriteLine("Update Triggered."); } catch (ObjectDisposedException e) { Console.WriteLine("ERROR: An error occurred when trying to trigger the update. Try restarting this VM, if it continues contact EXCON"); Console.WriteLine(e.ToString()); } }
public PipeClient(string handle, NxSim game) { PipeStream pipeClient = new AnonymousPipeClientStream(PipeDirection.In, handle); sr = new StreamReader(pipeClient); ev = EventWaitHandle.OpenExisting("NxPipe"); this.game = game; }
private void Button_Click(object sender, RoutedEventArgs e) { using (EventWaitHandle ewh = EventWaitHandle.OpenExisting(Controller.NotificationEvent.全通貨決済.ToString())) { // イベント通知 ewh.Set(); } }
public static void Main(string[] args) { EventWaitHandle waitHandle = EventWaitHandle.OpenExisting(transportStartedName); Run(); waitHandle.Set(); Console.Read(); }
private EventWaitHandle SetEventWaitHandle(string handleName) { EventWaitHandle ewh = null; try { ewh = EventWaitHandle.OpenExisting(handleName); } catch { ewh = new EventWaitHandle(false, EventResetMode.AutoReset, handleName); } return(ewh); }
public void OpenExisting_UnavailableName_Windows() { string name = Guid.NewGuid().ToString("N"); Assert.Throws <WaitHandleCannotBeOpenedException>(() => EventWaitHandle.OpenExisting(name)); EventWaitHandle ignored; Assert.False(EventWaitHandle.TryOpenExisting(name, out ignored)); }
static public void PleaseWaitEnd() { try { EventWaitHandle pleaseWaitDialogEvent = EventWaitHandle.OpenExisting("pleaseWaitDialogEvent"); pleaseWaitDialogEvent.Set(); } catch { } }