/// <summary> /// fired on kill of this process /// </summary> /// <param name="e"></param> private void OnConsoleEvent(ConsoleEvent e) { #region implementation switch (e) { case ConsoleEvent.CTRL_CLOSE: case ConsoleEvent.CTRL_C: case ConsoleEvent.CTRL_LOGOFF: case ConsoleEvent.CTRL_SHUTDOWN: IEnumerator ie = _childProcesses.Values.GetEnumerator(); while (ie.MoveNext()) { Process p = (Process)ie.Current; if (!p.HasExited) { p.Kill(); } p.Close(); } Process.GetCurrentProcess().Kill(); break; } #endregion }
private bool Handler(ConsoleEvent consoleEvent) { var args = new ConsoleEventArgs(consoleEvent); this.ControlEvent?.Invoke(this, args); return(args.Result); }
private bool BreakHandler(ConsoleEvent consoleEvent) { Debug.WriteLine(Thread.CurrentThread.ManagedThreadId, String.Format("PSEventingBreakHandler event: {0}", consoleEvent)); switch (consoleEvent) { case ConsoleEvent.CtrlC: m_ctrlCHit = true; if (m_captureCtrlC) { string emptyGuid = Guid.Empty.ToString(); PSQueueHelper.Instance.DefaultQueue.EnqueueEvent(emptyGuid, typeof(PSEventingBreakHandler), consoleEvent.ToString(), EventArgs.Empty); m_ctrlCHit = false; // bugfix: http://www.codeplex.com/PSEventing/WorkItem/View.aspx?WorkItemId=4856 // ctrl+c handling ends here (doens't get to powershell) return(true); } break; case ConsoleEvent.CtrlBreak: case ConsoleEvent.CtrlClose: case ConsoleEvent.CtrlLogoff: // unhook, we're going down Unhook(); break; default: // shutdown break; } // chain to next handler (e.g. consolehost) return(false); }
private void Handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) { ControlEvent(consoleEvent); } }
// Control Event Handler public static void OnControlEvent(ConsoleEvent consoleEvent) { Console.WriteLine("Event: {0}", consoleEvent); if (consoleEvent == ConsoleEvent.CTRL_CLOSE || consoleEvent == ConsoleEvent.CTRL_LOGOFF || consoleEvent == ConsoleEvent.CTRL_SHUTDOWN) { server.StopListening(); thr.Abort(); } }
private bool Handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) { return(ControlEvent(consoleEvent)); } return(false); }
public static void OnControlEvent(ConsoleEvent consoleEvent) { // Control-C doesn't debug well Interlocked.Decrement(ref isRunning); Console.WriteLine("Event: {0}", consoleEvent); Console.WriteLine("Thread closed gracefully"); ConfigTor.KillTor(); Thread.Sleep(500); }
private static int ConsoleCtrHandler(ConsoleEvent e) { SetConsoleCtrlHandler(handler, false); if (GameServer.Instance != null) { GameServer.Instance.Stop(); } return(0); }
private void HandleControlEvent(ConsoleEvent consoleEvent) { lock (this) { if (OnConsoleEvent != null) { OnConsoleEvent(this, EventArgs.Empty); } } }
private void HandleControlEvent(ConsoleEvent consoleEvent) { lock (this.SyncObject) { if (OnConsoleEvent != null) { OnConsoleEvent(this, EventArgs.Empty); } } }
/** * <summary>Whenever the user presses ctrl-c this is called by the * operating system.</summary> * <param name="signal">The signal number sent to the application</param> */ protected bool ConsoleEventHandler(ConsoleEvent console_event) { if (console_event != ConsoleEvent.CTRL_LOGOFF) { SetConsoleCtrlHandler(ConsoleEventHandler, false); Console.WriteLine("Receiving signal: {0}. Exiting", console_event); Exit(); } return(true); }
private void ErrorHandler(object sender, DataReceivedEventArgs e) { // Prepend line numbers to each line of the output. if (e.Data != null) { ConsoleEvent.Invoke(this, new CustomEventArgs { error = e.Data }); _outStr.Append("\r\n" + e.Data); } }
private bool handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) { var a = new ConsoleCtrlEventArgs(consoleEvent); a.CallDefaultHandler = true; ControlEvent(this, a); return(!a.CallDefaultHandler); } return(false); }
private T UnmarshalPayload <T>(ConsoleEvent e) { CheckNotDisposed(); if (e != Event) { throw new InvalidOperationException(); } if (_payload == null) { _payload = Marshal.PtrToStructure(_payloadPtr, typeof(T)); } return((T)_payload); }
private T UnmarshalPayload <T>(ConsoleEvent e) { CheckNotDisposed(); if (e != Event) { throw _session.Logger.WriteException(new InvalidOperationException("Payload type does not match with event")); } if (_payload == null) { _payload = Marshal.PtrToStructure(_payloadPtr, typeof(T)); } return((T)_payload); }
// Control Event Handler public static bool OnControlEvent(ConsoleEvent consoleEvent) { bool handled = false; switch (consoleEvent) { case ConsoleEvent.CTRL_SHUTDOWN: case ConsoleEvent.CTRL_CLOSE: try { YarSystem.Current.Stop(); handled = true; } catch (Exception ex) { YarSystem.WriteLog(ex.ToString()); } break; default: return(handled); } return(handled); }
internal ConsoleEvent GetNextEvent() { // TODO: How to handle timing events? ConsoleEvent ev = null; while (ev == null) { int whichEvent = WaitHandle.WaitAny(new[] { consoleEvent, clientEvent }); switch (whichEvent) { case 0: ev = GetConsoleEvent(); break; case 1: ev = GetClientEvent(); break; } if (!clientEventQueue.IsEmpty) { clientEvent.Set(); } } return(ev); }
public void Start() { IsEnded = false; // Server Event ConsoleEvent.Initialize(); // Socket serverSock = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); try { serverSock.Bind(new IPEndPoint(IPAddress.Any, Config.PORT)); serverSock.Listen(Config.MAX_NUM); // MySQL 연결 BootLoader.Initialize(); Msg.Info("서버가 정상적으로 실행되었습니다."); // 멀티쓰레드 시작 ServerThread.Initialize(); ServerThread.Start(); while (true) { allDone.Reset(); if (IsEnded) { serverSock.Close(0); break; } // 승인이 끝난 경우 AcceptCallBack을 실행 - 대상 소켓은 서버 소켓 serverSock.BeginAccept(new AsyncCallback(AcceptCallBack), serverSock); allDone.WaitOne(); } Msg.Close("Handler 정상 종료 완료."); } catch (Exception e) { Msg.Error(e.ToString()); } }
/// Constructor public ConsoleCtrlEventArgs(ConsoleEvent consoleEvent) { ConsoleEvent = consoleEvent; }
public async Task <string> Execute(string args) { Connecting conn = new Connecting(_exe, GetComParam() + args); CancellationTokenSource cts = new CancellationTokenSource(); var t = Task.Run(() => { string tempExeName = Path.Combine(ExePath, _exe); if (!File.Exists(Path.Combine(ExePath, "python37.dll")) || !Directory.Exists(Path.Combine(ExePath, "lib"))) { if (File.Exists(Path.Combine(ExePath, "python37.dll"))) { File.Delete(Path.Combine(ExePath, "python37.dll")); } if (Directory.Exists(Path.Combine(ExePath, "lib"))) { Directory.Delete(Path.Combine(ExePath, "lib"), true); } ZipFile.ExtractToDirectory(Path.Combine(ExePath, "cxfreeze.zip"), ExePath); } if (!File.Exists(Path.Combine(ExePath, "python37.dll"))) { ConsoleEvent.Invoke(this, new CustomEventArgs { error = "Python DLL is not loaded." }); } else if (!File.Exists(tempExeName)) { var errMsg = "[" + _exe + "] File '" + _exe + "' not found in directory " + ExePath + "! Unable to start request."; ConsoleEvent.Invoke(this, new CustomEventArgs { error = errMsg }); } else if (_com.Length < 3) { var errMsg = "[" + _exe + "] COM port is invalid (" + _com + ") - please select the right port and try again."; ConsoleEvent.Invoke(this, new CustomEventArgs { error = errMsg }); } else { int procId = 0; var stopwatch = new Stopwatch(); stopwatch.Start(); using (var p = new Process()) { try { using (cts.Token.Register(() => { p.Kill(); p.WaitForExit(500); p.Close(); p.Dispose(); })) { _outStr.Clear(); _outStr.Append(" >>> " + _exe + " " + GetComParam() + args + "\r\n"); ConsoleEvent.Invoke(this, new CustomEventArgs { input = _exe + " " + GetComParam() + args }); p.StartInfo = new ProcessStartInfo { FileName = tempExeName, UseShellExecute = false, WorkingDirectory = ExePath, WindowStyle = ProcessWindowStyle.Hidden, CreateNoWindow = true, Arguments = GetComParam() + args, RedirectStandardOutput = true, RedirectStandardError = true }; //p.StartInfo.RedirectStandardError = true; //p.OutputDataReceived += new DataReceivedEventHandler(OutputHandler); p.ErrorDataReceived += new DataReceivedEventHandler(ErrorHandler); p.Start(); //p.BeginOutputReadLine(); p.BeginErrorReadLine(); procId = p.Id; int dataReceived = 0; var sTemp = ""; var outputReadTask = Task.Run(() => { int iCh = 0; var s2 = ""; var s3 = ""; try { do { iCh = p.StandardOutput.Read(); if (iCh >= 0) { if (iCh == 8) { s3 = "\r\n"; s2 = " "; } else { s2 = s3 + char.ConvertFromUtf32(iCh); if (s3.Length > 0) { s3 = ""; } } sTemp += s2; } } while (iCh >= 0); } catch (Exception e) { var errMsg = "[" + _exe + "] Exception: " + e.Message; ConsoleEvent.Invoke(this, new CustomEventArgs { error = errMsg }); } }); do { try { if (sTemp.Length > 0) { dataReceived++; var s = sTemp; sTemp = ""; _outStr.Append(s); ConsoleEvent.Invoke(this, new CustomEventArgs { output = s }); } else { p.WaitForExit(200); } } catch (Exception) { } if (dataReceived == 0 && stopwatch.ElapsedMilliseconds > 3000) { ConsoleEvent.Invoke(this, new CustomEventArgs { error = "Request timeout." }); break; } } while (!p.HasExited); if (sTemp.Length > 0) { _outStr.Append(sTemp); ConsoleEvent.Invoke(this, new CustomEventArgs { output = sTemp }); } } } catch (Exception ex) { ConsoleEvent.Invoke(this, new CustomEventArgs { error = ex.Message }); } try { p.Close(); } catch (Exception) { } } stopwatch.Stop(); long elapsed_time = stopwatch.ElapsedMilliseconds; ConsoleEvent.Invoke(this, new CustomEventArgs { input = " [ execution time ] " + (elapsed_time / 1000.0) + " s" }); try { if (Process.GetProcessesByName(_exe.Replace(".exe", "")).Length > 0) { Process.GetProcessesByName(_exe.Replace(".exe", ""))[0].Kill(); } } catch (Exception) { } } Connecting.Terminate(); }, cts.Token); conn.ShowDialog(); if (!t.IsCompleted) // was aborted { ConsoleEvent.Invoke(this, new CustomEventArgs { error = "Request aborted." }); cts.Cancel(); t.Wait(500); } return(await Task.FromResult(_outStr.ToString())); }
internal void PostEvent(ConsoleEvent @event) { clientEventQueue.Enqueue(@event); clientEvent.Set(); }
private bool Handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) return ControlEvent(consoleEvent); return false; }
public ConsoleEventArgs(ConsoleEvent consoleEvent) { this.ConsoleEvent = consoleEvent; }
public static void OnControlEvent(ConsoleEvent consoleEvent) { FinderHandler.Terminate(null, null); }
private static void Handler(ConsoleEvent consoleEvent) { commandlet.Terminate(); Process.GetCurrentProcess().Kill(); }
/// <summary> Обработчик события от консоли. Обработчик должен быстро завершаться. </summary> /// <param name="consoleEvent"> Возникшее событие. </param> private void OnControlEvent(ConsoleEvent consoleEvent) => _action(consoleEvent);
/// Constructor public ConsoleCtrlEventArgs(ConsoleEvent consoleEvent ) { ConsoleEvent = consoleEvent; }
private void Handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) ControlEvent(consoleEvent); }
/// <summary> /// Is called whenever a Ctrl-C is caught from the console. Ignored /// </summary> /// <param name="consoleEvent"></param> /// <returns></returns> private bool CtrlCHandler( ConsoleEvent consoleEvent) // I Encapsulates the console event received { return(true); }
private static int ConsoleCtrHandler(ConsoleEvent e) { SetConsoleCtrlHandler(handler, false); if (GameServer.Instance != null) GameServer.Instance.Stop(); return 0; }
protected virtual void SendConsoleEvent(ConsoleEventArgs args) { ConsoleEvent?.Invoke(this, args); }
/** <summary>Whenever the user presses ctrl-c this is called by the operating system.</summary> <param name="signal">The signal number sent to the application</param> */ protected bool ConsoleEventHandler(ConsoleEvent console_event) { if(console_event != ConsoleEvent.CTRL_LOGOFF) { SetConsoleCtrlHandler(ConsoleEventHandler, false); Console.WriteLine("Receiving signal: {0}. Exiting", console_event); Exit(); } return true; }
public static void MyEventHandler(ConsoleEvent consoleEvent) { Console.WriteLine("Event handler output: event fired = {0}", consoleEvent); }
private bool handler(ConsoleEvent consoleEvent) { if (ControlEvent != null) { var a = new ConsoleCtrlEventArgs(consoleEvent); a.CallDefaultHandler = true; ControlEvent(this, a); return !a.CallDefaultHandler; } return false; }