-
-
Notifications
You must be signed in to change notification settings - Fork 747
Expand file tree
/
Copy pathProcessRunner.cs
More file actions
595 lines (511 loc) · 18 KB
/
ProcessRunner.cs
File metadata and controls
595 lines (511 loc) · 18 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
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
namespace ElectronNET.Common
{
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// Class encapsulating out-of-process execution of console applications.
/// </summary>
/// <remarks>
/// Why this class?
/// Probably everybody who has tried to use System.Diagnotics.Process cross-platform and with reading
/// stderr and stdout will know that it is a pretty quirky API.
/// The code below may look weird, even non-sensical, but it works 100% reliable with all .net frameworks
/// and .net versions and on every platform where .net runs. This is just the innermost core, that's why
/// there are many dead ends, but it has all the crucial parts.
/// </remarks>
/// <seealso cref="IDisposable" />
[SuppressMessage("ReSharper", "SuspiciousLockOverSynchronizationPrimitive")]
public class ProcessRunner : IDisposable
{
private volatile Process process;
private readonly StringBuilder stdOut = new StringBuilder(4 * 1024);
private readonly StringBuilder stdErr = new StringBuilder(4 * 1024);
private volatile ManualResetEvent stdOutEvent;
private volatile ManualResetEvent stdErrEvent;
private volatile Stopwatch stopwatch;
/// <summary>Initializes a new instance of the <see cref="ProcessRunner" /> class.</summary>
/// <param name="name">A name identifying the process to execute.</param>
public ProcessRunner(string name)
{
this.Name = name;
}
public event EventHandler<EventArgs> ProcessExited;
public bool IsDisposed { get; private set; }
private Process Process
{
get
{
return this.process;
}
}
public bool IsRunning
{
get
{
var proc = this.process;
if (proc != null)
{
try
{
return !proc.HasExited;
}
catch
{
return false;
}
}
return false;
}
}
/// <summary>Gets the name identifying the process.</summary>
/// <value>The name.</value>
public string Name { get; }
public string CommandLine { get; private set; }
public string ExecutableFileName { get; private set; }
public string WorkingFolder { get; private set; }
public bool RecordStandardOutput { get; set; }
public bool RecordStandardError { get; set; }
public string StandardOutput
{
get
{
lock (this.stdOut)
{
return this.stdOut.ToString();
}
}
}
public string StandardError
{
get
{
lock (this.stdErr)
{
return this.stdErr.ToString();
}
}
}
public int? LastExitCode { get; private set; }
public bool Run(string exeFileName, string commandLineArgs, string workingDirectory)
{
this.CommandLine = commandLineArgs;
this.WorkingFolder = workingDirectory;
this.ExecutableFileName = exeFileName;
var startInfo = new RunnerParams(exeFileName)
{
Arguments = commandLineArgs,
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardError = true,
RedirectStandardInput = true,
ErrorDialog = false,
CreateNoWindow = true,
WorkingDirectory = workingDirectory
};
return this.Run(startInfo);
}
protected bool Run(RunnerParams runnerParams)
{
if (this.IsDisposed)
{
throw new ObjectDisposedException(this.GetType().ToString());
}
this.Close();
this.LastExitCode = null;
lock (this.stdOut)
{
this.stdOut.Clear();
}
lock (this.stdErr)
{
this.stdErr.Clear();
}
this.stdOutEvent = new ManualResetEvent(false);
this.stdErrEvent = new ManualResetEvent(false);
if (!this.OnBeforeStartProcessCore(runnerParams))
{
return false;
}
var startInfo = new ProcessStartInfo(runnerParams.FileName)
{
Arguments = runnerParams.Arguments,
UseShellExecute = runnerParams.UseShellExecute,
RedirectStandardOutput = runnerParams.RedirectStandardOutput,
RedirectStandardError = runnerParams.RedirectStandardError,
RedirectStandardInput = runnerParams.RedirectStandardInput,
ErrorDialog = runnerParams.ErrorDialog,
CreateNoWindow = runnerParams.CreateNoWindow,
WorkingDirectory = runnerParams.WorkingDirectory
};
foreach (var variableSetting in runnerParams.EnvironmentVariables)
{
startInfo.EnvironmentVariables[variableSetting.Key] = variableSetting.Value;
}
var proc = new Process { StartInfo = startInfo };
proc.EnableRaisingEvents = true;
this.RegisterProcessEvents(proc);
this.process = proc;
try
{
this.process.Start();
this.stopwatch = Stopwatch.StartNew();
this.process.BeginOutputReadLine();
this.process.BeginErrorReadLine();
this.process.Refresh();
this.OnProcessStartedCore();
}
catch (Exception ex)
{
this.OnProcessErrorCore(ex);
this.Close();
throw;
}
return true;
}
public async Task<bool> WriteAsync(string data)
{
var proc = this.Process;
if (proc != null && !proc.HasExited)
{
try
{
await proc.StandardInput.WriteAsync(data).ConfigureAwait(false);
return true;
}
catch (Exception ex)
{
Console.WriteLine("{0}.{1}: {2}", ex, nameof(ProcessRunner), nameof(this.WriteAsync));
}
}
return false;
}
public bool WaitForExit()
{
var proc = this.process;
if (proc == null)
{
return true;
}
try
{
// Wait for process and all I/O to finish.
proc.WaitForExit();
return true;
}
catch (Exception ex)
{
this.OnProcessErrorCore(ex);
return false;
}
}
/// <summary>Sychronously waits for the specified amount and ends the process afterwards.</summary>
/// <param name="timeoutMs">The timeout ms.</param>
/// <remarks>This method allows for a clean exit, since it also waits until the StandardOutput and
/// StandardError pipes are processed to the end.</remarks>
/// <returns>true, if the process has exited gracefully; false otherwise.</returns>
public bool WaitAndKill(int timeoutMs)
{
var proc = this.process;
if (proc == null)
{
return true;
}
try
{
if (timeoutMs <= 0)
{
throw new ArgumentException("Argument must be greater then 0", nameof(timeoutMs));
}
// Timed waiting. We need to wait for I/O ourselves.
if (!proc.WaitForExit(timeoutMs))
{
this.Cancel();
}
// Wait for the I/O to finish.
var waitMs = (int)(timeoutMs - this.stopwatch.ElapsedMilliseconds);
waitMs = Math.Max(waitMs, 10);
this.stdOutEvent?.WaitOne(waitMs);
waitMs = (int)(timeoutMs - this.stopwatch.ElapsedMilliseconds);
waitMs = Math.Max(waitMs, 10);
return this.stdErrEvent?.WaitOne(waitMs) ?? false;
}
finally
{
// Cleanup.
this.Cancel();
}
}
/// <summary>Asynchronously waits for the specified amount and ends the process afterwards.</summary>
/// <param name="timeoutMs">The timeout ms.</param>
/// <remarks>Tjhis method performs the wait operation on a threadpool thread.
/// Only recommended for short timeouts and situations where a synchronous call is undesired.</remarks>
/// <returns>true, if the process has exited gracefully; false otherwise.</returns>
public Task<bool> WaitAndKillAsync(int timeoutMs)
{
var task = Task.Run(() => this.WaitAndKill(timeoutMs));
return task;
}
/// <summary>Waits asynchronously for the process to exit.</summary>
/// <param name="timeoutMs">The timeout ms.</param>
/// <param name="cancellationToken">The cancellation token.</param>
/// <returns>true, if the process has exited, false if the process is still running.</returns>
/// <remarks>
/// This methods waits until the process has existed or the
/// <paramref name="timeoutMs" /> has elapsed.
/// This method does not end the process itself.
/// </remarks>
public Task<bool> WaitForExitAsync(int timeoutMs, CancellationToken cancellationToken = default)
{
timeoutMs = Math.Max(0, timeoutMs);
var timeoutSource = new CancellationTokenSource(timeoutMs);
var linkedSource = CancellationTokenSource.CreateLinkedTokenSource(timeoutSource.Token, cancellationToken);
return this.WaitForExitAsync(linkedSource.Token);
}
/// <summary>Waits asynchronously for the process to exit.</summary>
/// <param name="cancellationToken">The cancellation token.</param>
/// <remarks>This methods waits until the process has existed or the
/// <paramref name="cancellationToken"/> has been triggered.
/// This method does not end the process itself.</remarks>
/// <returns>true, if the process has exited, false if the process is still running.</returns>
public async Task<bool> WaitForExitAsync(CancellationToken cancellationToken = default)
{
var proc = this.process;
if (proc == null)
{
return true;
}
var tcs = new TaskCompletionSource<bool>();
// Use local function instead of a lambda to allow proper deregistration of the event
void ProcessExited(object sender, EventArgs e)
{
tcs.TrySetResult(true);
}
try
{
proc.EnableRaisingEvents = true;
proc.Exited += ProcessExited;
if (proc.HasExited)
{
return true;
}
using (cancellationToken.Register(() => tcs.TrySetResult(false)))
{
return await tcs.Task.ConfigureAwait(false);
}
}
finally
{
proc.Exited -= ProcessExited;
}
}
public void Cancel()
{
var proc = this.process;
if (proc != null)
{
try
{
// Invalidate cached data to requery.
proc.Refresh();
// We need to do this in case of a non-UI proc
// or one to be forced to cancel.
if (!proc.HasExited)
{
// Cancel all pending IO ops.
proc.CancelErrorRead();
proc.CancelOutputRead();
}
if (!proc.HasExited)
{
proc.Kill();
}
}
catch
{
// Kill will throw when/if the process has already exited.
}
}
var outEvent = this.stdOutEvent;
this.stdOutEvent = null;
if (outEvent != null)
{
lock (outEvent)
{
outEvent.Close();
outEvent.Dispose();
}
}
var errEvent = this.stdErrEvent;
this.stdErrEvent = null;
if (errEvent != null)
{
lock (errEvent)
{
errEvent.Close();
errEvent.Dispose();
}
}
}
private void Close()
{
this.Cancel();
var proc = this.process;
this.process = null;
if (proc != null)
{
try
{
this.UnRegisterProcessEvents(proc);
// Dispose in all cases.
proc.Close();
proc.Dispose();
}
catch (Exception ex)
{
this.OnProcessErrorCore(ex);
}
}
}
protected virtual void OnDispose()
{
}
void IDisposable.Dispose()
{
this.IsDisposed = true;
this.Close();
this.OnDispose();
}
public override string ToString()
{
return string.Format("{0}: {1} {2}", this.GetType().Name, this.Name, this.process);
}
protected virtual bool OnBeforeStartProcessCore(RunnerParams processRunnerInfo)
{
return true;
}
protected virtual void OnProcessStartedCore()
{
}
protected virtual void OnProcessErrorCore(Exception processException)
{
}
protected virtual void OnProcessExitCore(int exitCode)
{
}
private void RegisterProcessEvents(Process proc)
{
proc.ErrorDataReceived += this.Process_ErrorDataReceived;
proc.OutputDataReceived += this.Process_OutputDataReceived;
proc.Exited += this.Process_Exited;
}
private void UnRegisterProcessEvents(Process proc)
{
proc.ErrorDataReceived -= this.Process_ErrorDataReceived;
proc.OutputDataReceived -= this.Process_OutputDataReceived;
proc.Exited -= this.Process_Exited;
}
private void Process_Exited(object sender, EventArgs e)
{
this.WaitForExitAfterExited();
this.SetExitCode();
this.OnProcessExitCore(this.LastExitCode ?? -9998);
this.ProcessExited?.Invoke(this, new EventArgs());
}
private void WaitForExitAfterExited()
{
try
{
// This shouldn't throw here, but the mono process implementation doesn't always behave as it should.
this.process.WaitForExit();
}
catch (Exception ex)
{
Console.WriteLine("Error when calling WaitForExit after exited event has fired: {0}.{1}: {2}", ex, nameof(ProcessRunner), nameof(this.WaitForExitAfterExited));
}
}
private void SetExitCode()
{
int exitCode = -9999;
try
{
if (this.Process != null)
{
exitCode = this.Process.ExitCode;
}
}
catch
{
// Ignore error.
}
this.LastExitCode = exitCode;
}
private void Process_ErrorDataReceived(object sender, DataReceivedEventArgs e)
{
if (this.RecordStandardError)
{
lock (this.stdErr)
{
this.stdErr.AppendLine(e.Data);
}
}
if (e.Data != null)
{
Console.WriteLine("|| " + e.Data);
}
else
{
var evt = this.stdErrEvent;
if (evt != null)
{
lock (evt)
{
try
{
evt.Set();
}
catch
{
// Ignore error.
}
}
}
}
}
private void Process_OutputDataReceived(object sender, DataReceivedEventArgs e)
{
if (this.RecordStandardOutput)
{
lock (this.stdOut)
{
this.stdOut.AppendLine(e.Data);
}
}
if (e.Data != null)
{
Console.WriteLine("|| " + e.Data);
}
else
{
var evt = this.stdOutEvent;
if (evt != null)
{
lock (evt)
{
try
{
evt.Set();
}
catch
{
// Ignore error.
}
}
}
}
}
}
}