-
Notifications
You must be signed in to change notification settings - Fork 11
Expand file tree
/
Copy pathExecute.cs
More file actions
183 lines (159 loc) · 7.76 KB
/
Execute.cs
File metadata and controls
183 lines (159 loc) · 7.76 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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
namespace FFBitrateViewer
{
public class ExecStatus
{
public int Code = 0;
public string StdErr = "";
public string StdOut = "";
}
public enum ExecStop
{
None = 0,
Timeout = 1,
Cancel = 2
}
class Execute
{
private readonly static int TimeoutDefault = 5000; // milliseconds
private readonly static int TimeoutNoOutput = 15_000; // milliseconds
private readonly static int TimeoutStep = 200; // milliseconds
public static ExecStatus Exec(string executable, string args, int? timeout = null, CancellationToken? cancellationToken = null, Action<string>? stdoutAction = null, Action<string>? stderrAction = null)
{
string func = "Execute.Exec";
Log.WriteCommand(executable, args);
Log.Write(LogLevel.DEBUG, func + ": Started", executable, args);
var result = new ExecStatus();
var stdout = new StringBuilder();
var stderr = new StringBuilder();
int time1 = 0;
int time2 = 0;
int timeout1 = timeout ?? TimeoutDefault;
int timeout2 = TimeoutNoOutput;
using (var stdoutWaitHandle = new AutoResetEvent(false))
using (var stderrWaitHandle = new AutoResetEvent(false))
{
using (Process process = new())
{
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.EnableRaisingEvents = false;
process.StartInfo.FileName = executable;
process.StartInfo.Arguments = args;
process.StartInfo.WorkingDirectory = AppDomain.CurrentDomain.BaseDirectory;
// To prevent deadlock, at least one stream (stdout or stderr) must be redirected (read async, I'm redirecting both):
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.standardoutput?view=netframework-4.7.2
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.RedirectStandardError = true;
try
{
process.OutputDataReceived += (sender, e) =>
{
time2 = 0;
if (string.IsNullOrEmpty(e.Data)) stdoutWaitHandle.Set();
else
{
#if DEBUG
// Debug.WriteLine("StdOut: " + e.Data); // very slow
#endif
if (stdoutAction == null) stdout.AppendLine(e.Data);
else stdoutAction(e.Data);
}
};
process.ErrorDataReceived += (sender, e) =>
{
time2 = 0;
if (string.IsNullOrEmpty(e.Data)) stderrWaitHandle.Set();
else
{
#if DEBUG
// Debug.WriteLine("StdErr: " + e.Data); // very slow
#endif
if (stderrAction == null) stderr.AppendLine(e.Data);
else stderrAction(e.Data);
}
};
process.Start();
//process.Refresh();
process.PriorityClass = ProcessPriorityClass.BelowNormal;
process.BeginOutputReadLine();
process.BeginErrorReadLine();
ExecStop stopped = ExecStop.None;
do
{
time1 += TimeoutStep;
time2 += TimeoutStep;
if (time1 > timeout1 || time2 > timeout2)
{
Log.Write(LogLevel.DEBUG, func + ": Timed out");
stopped = ExecStop.Timeout;
result.Code = -2;
result.StdErr = "Timed out";
break;
}
if (cancellationToken != null && ((CancellationToken)cancellationToken).IsCancellationRequested) // todo@ cancellationToken.ThrowIfCancellationRequested()
{
Log.Write(LogLevel.DEBUG, func + ": Cancellation request received");
stopped = ExecStop.Cancel;
result.Code = -4;
result.StdErr = "Cancelled";
break;
}
} while (!process.WaitForExit(TimeoutStep));
if (stopped == ExecStop.None)
{
process.WaitForExit(); // double checking
process.Refresh();
result.Code = process.HasExited ? process.ExitCode : -3;
Log.Write(LogLevel.DEBUG, func + ": Exited (" + result.Code + ")");
// Sometimes ExitCode = -1073741819 (caused by LAVSplitter -- check windows Application Log)
//if (result.Code != 0) throw new InvalidOperationException();
result.StdOut = stdout.ToString();
Log.Write(LogLevel.DEBUG, func + ": StdOut=" + result.StdOut);
result.StdErr = stderr.ToString();
Log.Write(LogLevel.DEBUG, func + ": StdErr=" + result.StdErr);
if (result.Code != 0 && string.IsNullOrEmpty(result.StdErr)) result.StdErr = "Could not get any output";
}
else
{
process.CancelOutputRead();
process.CancelErrorRead();
stdoutWaitHandle.Set();
stderrWaitHandle.Set();
Log.Write(LogLevel.DEBUG, func + ": Closing external program");
if (process.CloseMainWindow())
{
Log.Write(LogLevel.DEBUG, func + ": External program closed successfully");
}
else
{
Log.Write(LogLevel.DEBUG, func + ": Unable to close external program. Killing it");
process.Kill();
}
process.WaitForExit();
process.Refresh();
}
}
catch (Exception e)
{
Log.Write(LogLevel.ERROR, func + ": exception", e.Message);
result.Code = -1;
result.StdErr = e.Message;
stdoutWaitHandle.Set();
stderrWaitHandle.Set();
}
finally
{
stdoutWaitHandle.WaitOne(timeout1);
stderrWaitHandle.WaitOne(timeout1);
}
}
}
Log.Write(LogLevel.DEBUG, func + ": Finished. stdout=" + result.StdOut + ", stderr=" + result.StdErr + " (" + result.Code + ")");
return result;
}
}
}