Skip to content

Commit

Permalink
Harden killing of processes by catching relevant exceptions. (#1)
Browse files Browse the repository at this point in the history
* Harden killing of processes by catching relevant exceptions.
* Add logging in ProgressInfoProcessManager.
* Add annotations.
  • Loading branch information
andre-amagno authored Jul 31, 2024
1 parent 2ebb672 commit c087543
Showing 1 changed file with 40 additions and 5 deletions.
Original file line number Diff line number Diff line change
@@ -1,13 +1,14 @@
using JetBrains.Annotations;

using System;
using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Linq;
using AmagnoVirtualPrinter.Agent.Core.Interfaces;
using AmagnoVirtualPrinter.Logging;
using AmagnoVirtualPrinter.ProgressInfo.Lib.Interfaces;
using AmagnoVirtualPrinter.Utils;
using JetBrains.Annotations;

namespace AmagnoVirtualPrinter.ProgressInfo.Lib
{
Expand All @@ -16,6 +17,14 @@ public class ProgressInfoProcessManager : IProgressInfoProcessManager
{
private const string ProcessName = "AmagnoPrinterAgentProgress";

[NotNull]
private readonly IVirtualPrinterLogger<ProgressInfoProcessManager> _logger;

public ProgressInfoProcessManager([NotNull]IVirtualPrinterLogger<ProgressInfoProcessManager> logger)
{
_logger = logger;
}

public bool IsRunning()
{
return Process.GetProcesses().Any(pList => pList.ProcessName.Contains(ProcessName));
Expand All @@ -37,10 +46,36 @@ public void Stop()
{
var processes = Process.GetProcesses().Where(pList => pList.ProcessName.Contains(ProcessName));

foreach(var process in processes)
foreach (var process in processes)
{
KillProcess(process);
}
}

private void KillProcess([NotNull]Process process)
{
try
{
process.Kill();
}
catch (Win32Exception exception)
{
// The associated process could not be terminated. -or-
// The process is terminating. -or-
// The associated process is a Win16 executable.
LogWarn(exception, "Failed to kill process while printing");
}
catch (InvalidOperationException exception)
{
// The process has already exited. -or-
// There is no process associated.
LogWarn(exception, "Failed to kill process while printing");
}
}

private void LogWarn(Exception exception, string message)
{
_logger.Warn("{message}:\r\nException: {exception}", message, exception);
}
}
}
}

0 comments on commit c087543

Please sign in to comment.