public async Task <bool> KillConsoleProcessAsync() { try { if ((!_process.HasExited) && (!_nConsoleProcessExitCode.HasValue)) { GetInfoRoot rootinfo = await GetInfoRoot.QueryAsync(this); if (!rootinfo.Pid.HasValue) { return(false); // Has already exited } try { Process.GetProcessById((int)rootinfo.Pid.Value).Kill(); return(true); } catch (Exception) { // Most likely, has already exited } } } catch (Exception) { // Might be a race, so in between HasExited and Kill state could change, ignore possible errors here } return(false); }
/// <summary> /// Async-loop retries for getting the root payload process to await its exit. /// </summary> private async Task <int?> Init_PayloadProcessMonitoring_WaitForExitCodeAsync() { for (;;) { // Might have been terminated on the main thread if (_nConsoleProcessExitCode.HasValue) { return(null); } if (_process.HasExited) { return(null); } try { // Ask ConEmu for PID GetInfoRoot rootinfo = await GetInfoRoot.QueryAsync(this); // Check if the process has extied, then we're done if (rootinfo.ExitCode.HasValue) { return(rootinfo.ExitCode.Value); } // If it has started already, must get a PID // Await till the process exits and loop to reask conemu for its result // If conemu exits too in this time, then it will republish payload exit code as its own exit code, and implementation will use it if (rootinfo.Pid.HasValue) { await WinApi.Helpers.WaitForProcessExitAsync(rootinfo.Pid.Value); continue; // Do not wait before retrying } } catch (Exception) { // Smth failed, wait and retry } // Await before retrying once more await Task.Delay(TimeSpan.FromMilliseconds(10)); } }