From 7c1cbb44f8762a658010d511313f68988b29f7ef Mon Sep 17 00:00:00 2001 From: Phoenix Date: Fri, 27 Dec 2024 15:53:22 +0800 Subject: [PATCH] Add API endpoint to kill processes by ID with error handling --- Worker.cs | 35 +++++++++++++++++++++++++++++++++++ 1 file changed, 35 insertions(+) diff --git a/Worker.cs b/Worker.cs index b7adef5..2fa0983 100644 --- a/Worker.cs +++ b/Worker.cs @@ -59,6 +59,41 @@ namespace ResourceMonitorService await context.Response.WriteAsync(json); }); + app.MapPost("/api/kill-process", async context => + { + try + { + var idStr = await new StreamReader(context.Request.Body).ReadToEndAsync(); + int processId = Convert.ToInt32(idStr); + + Process[] processes = Process.GetProcesses().Where(p => p.Id == processId).ToArray(); + + if (processes.Length > 0) + { + foreach (var process in processes) + { + try + { + process.Kill(); + await context.Response.WriteAsync($"Process with ID {processId} has been killed."); + } + catch (Exception ex) + { + await context.Response.WriteAsync($"Error killing process with ID {processId}: {ex.Message}"); + } + } + } + else + { + await context.Response.WriteAsync($"No process found with ID {processId}."); + } + } + catch (Exception ex) + { + await context.Response.WriteAsync($"An error occurred: {ex.Message}"); + } + }); + _ = app.RunAsync(stoppingToken); await Task.Delay(Timeout.Infinite, stoppingToken);