-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProgram.cs
More file actions
74 lines (66 loc) · 2.15 KB
/
Program.cs
File metadata and controls
74 lines (66 loc) · 2.15 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading;
namespace ProcessWatchdog
{
class Program
{
static void Main(string[] args)
{
try
{
int parentId = Convert.ToInt32(args[0]);
string childProcessFilePath = Path.GetFullPath(args[1]);
WatchProcess(parentId, childProcessFilePath);
}
catch
{
Console.WriteLine("Expected two arguments: <PID> <ChildFilePath>");
}
}
static void WatchProcess(int parentId, string childProcessFilePath)
{
WaitForExit(parentId);
var processes = GetChildProcesses(childProcessFilePath);
foreach (var child in processes)
{
try
{
Console.WriteLine($"Shutting down child process {child.Id}");
child.Kill();
}
catch (Exception e)
{
Console.WriteLine($"Error {e.Message}");
}
}
}
static void WaitForExit(int processId)
{
while (Process.GetProcesses().Where(process => process.Id == processId).Count() == 1)
{
Console.WriteLine($"Parent process {processId} alive.");
Thread.Sleep(TimeSpan.FromSeconds(5));
}
Console.WriteLine($"Parent process {processId} exited.");
}
static IEnumerable<Process> GetChildProcesses(string path)
{
if (File.Exists(path))
{
var ids = File.ReadAllLines(path)
.Select(line => Convert.ToInt32(line))
.ToHashSet();
var processes = Process.GetProcesses().Where(process => ids.Contains(process.Id));
return processes;
}
else
{
return Enumerable.Empty<Process>();
}
}
}
}