forked from fifonik/FFBitrateViewer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathExecute.cs
More file actions
183 lines (159 loc) · 7.99 KB
/
Execute.cs
File metadata and controls
183 lines (159 loc) · 7.99 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
#define EXECUTE_WITH_CANCELLATION_TOKEN
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 = "";
}
class Execute
{
private readonly static int TimeoutDefault = 5000; // 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();
timeout ??= TimeoutDefault;
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) =>
{
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) =>
{
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();
#if EXECUTE_WITH_CANCELLATION_TOKEN
bool cancelled = false;
int time = 0;
do
{
if (cancellationToken != null && ((CancellationToken)cancellationToken).IsCancellationRequested) // todo@ cancellationToken.ThrowIfCancellationRequested()
{
Log.Write(LogLevel.DEBUG, func + ": Cancellation request received");
cancelled = true;
process.CancelOutputRead();
process.CancelErrorRead();
stdoutWaitHandle.Set();
stderrWaitHandle.Set();
break;
}
time += TimeoutStep;
if (time > timeout) break;
} while (!process.WaitForExit(TimeoutStep));
if (cancelled)
{
Log.Write(LogLevel.DEBUG, func + ": Cancellation request received, trying to close external program...");
if (process.CloseMainWindow())
{
Log.Write(LogLevel.DEBUG, func + ": External program closed successfully");
}
else
{
Log.Write(LogLevel.DEBUG, func + ": External program closing failed. Killing it");
process.Kill();
}
process.WaitForExit();
}
else
{
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();
result.StdErr = stderr.ToString();
Log.Write(LogLevel.DEBUG, func + ": StdOut=" + result.StdOut);
Log.Write(LogLevel.DEBUG, func + ": StdErr=" + result.StdErr);
if (result.Code != 0 && string.IsNullOrEmpty(result.StdErr)) result.StdErr = "Could not get any output";
}
#else
if (process.WaitForExit((int)timeout))
{
process.WaitForExit(); // checking
process.Refresh(); // checking
result.Code = process.HasExited ? process.ExitCode : -3;
result.StdOut = stdout.ToString();
result.StdErr = stderr.ToString();
Log.Write(LogLevel.DEBUG, func + ": StdOut=" + result.StdOut);
Log.Write(LogLevel.DEBUG, func + ": StdErr=" + result.StdErr);
if (result.Code != 0 && string.IsNullOrEmpty(result.StdErr)) result.StdErr = "Could not get any output";
}
else
{
// Timed out
result.Code = -2;
result.StdErr = "Timed out";
}
#endif
Debug.WriteLine("Finished");
}
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((int)timeout);
stderrWaitHandle.WaitOne((int)timeout);
}
}
}
Log.Write(LogLevel.DEBUG, func + ": Finished. stdout=" + result.StdOut + ", stderr=" + result.StdErr + "(" + result.Code + ")");
return result;
}
}
}