diff --git a/src/ES.SFTP.Host/SSH/SSHService.cs b/src/ES.SFTP.Host/SSH/SSHService.cs index d6b1e27..8bb9662 100644 --- a/src/ES.SFTP.Host/SSH/SSHService.cs +++ b/src/ES.SFTP.Host/SSH/SSHService.cs @@ -25,6 +25,7 @@ public class SSHService : IHostedService, INotificationHandler logger, IMediator mediator) @@ -163,6 +164,21 @@ private async Task UpdateHostKeyFiles() private async Task StartOpenSSH() { _logger.LogInformation("Starting 'sshd' process"); + _serviceProcessExitAction = () => + { + _logger.LogWarning("'sshd' process has stopped. Restarting process."); + RestartService().Wait(); + }; + + void ListenForExit() + { + //Use this approach since the Exited event does not trigger on process crash + Task.Run(() => + { + _serverProcess.WaitForExit(); + _serviceProcessExitAction?.Invoke(); + }); + } _serverProcess = new Process { StartInfo = @@ -180,6 +196,7 @@ private async Task StartOpenSSH() _serverProcess.OutputDataReceived += OnSSHOutput; _serverProcess.ErrorDataReceived += OnSSHOutput; _serverProcess.Start(); + ListenForExit(); _serverProcess.BeginOutputReadLine(); _serverProcess.BeginErrorReadLine(); await _mediator.Publish(new ServerStartupEvent()); @@ -198,6 +215,7 @@ private async Task StopOpenSSH(bool force = false) if (_serverProcess != null) { _logger.LogDebug("Stopping 'sshd' process"); + _serviceProcessExitAction = null; _serverProcess.Kill(true); _serverProcess.OutputDataReceived -= OnSSHOutput; _serverProcess.ErrorDataReceived -= OnSSHOutput;