-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExternalProcess.cs
More file actions
555 lines (512 loc) · 18.9 KB
/
ExternalProcess.cs
File metadata and controls
555 lines (512 loc) · 18.9 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
#region Related components
using System;
using System.IO;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Runtime.InteropServices;
#endregion
namespace net.vieapps.Components.Utility
{
/// <summary>
/// Servicing class for working with external processes
/// </summary>
public sealed class ExternalProcess
{
/// <summary>
/// Starts to run an external process directly
/// </summary>
/// <param name="filePath">The absolute path to the file of external process</param>
/// <param name="arguments">The arguments</param>
/// <param name="workingDirectory">The working directory</param>
/// <param name="onExited">The action to run when the process was exited (Exited event)</param>
/// <param name="onOutputDataReceived">The action to run when an output message was received (OutputDataReceived event)</param>
/// <param name="onErrorDataReceived">The action to run when an error message was received (ErrorDataReceived event)</param>
/// <param name="captureOutput">true to capture output (standard output and error output) as string</param>
/// <returns></returns>
/// <remarks>
/// Remember assign execution permisions to the file (sudo chmod 777 'filename') while running on Linux/macOS
/// </remarks>
public static Info Start(string filePath, string arguments, string workingDirectory = null, Action<object, EventArgs> onExited = null, Action<object, DataReceivedEventArgs> onOutputDataReceived = null, Action<object, DataReceivedEventArgs> onErrorDataReceived = null, bool captureOutput = false)
{
// prepare information
var info = new Info(filePath, arguments);
// prepare the process
var psi = new ProcessStartInfo
{
FileName = info.FilePath,
Arguments = info.Arguments,
WindowStyle = ProcessWindowStyle.Hidden,
CreateNoWindow = true,
UseShellExecute = false,
ErrorDialog = false,
RedirectStandardInput = true,
RedirectStandardOutput = true,
RedirectStandardError = true
};
if (string.IsNullOrWhiteSpace(workingDirectory))
{
workingDirectory = "";
if (!filePath.IsStartsWith("cmd.exe") && !filePath.IsStartsWith("/bin/bash") && !filePath.IsStartsWith("/bin/sh") && !filePath.IsStartsWith("/bin/zsh") && !filePath.IsStartsWith($".{Path.DirectorySeparatorChar}"))
{
var path = filePath;
var pos = path.IndexOf(Path.DirectorySeparatorChar);
while (pos > -1)
{
workingDirectory += path.Left(pos + 1);
path = path.Remove(0, pos + 1);
pos = path.IndexOf(Path.DirectorySeparatorChar);
}
if (workingDirectory.IsEndsWith(Path.DirectorySeparatorChar))
workingDirectory = workingDirectory.Left(workingDirectory.Length - 1);
}
}
if (!string.IsNullOrWhiteSpace(workingDirectory))
psi.WorkingDirectory = workingDirectory;
// initialize the proces
var process = new Process
{
StartInfo = psi,
EnableRaisingEvents = true
};
process.OutputDataReceived += (sender, args) =>
{
if (captureOutput)
info.StandardOutput += $"\r\n{args.Data}";
onOutputDataReceived?.Invoke(sender, args);
};
process.ErrorDataReceived += (sender, args) =>
{
if (captureOutput)
info.StandardError += $"\r\n{args.Data}";
onErrorDataReceived?.Invoke(sender, args);
};
process.Exited += (sender, args) =>
{
try
{
info.ExitCode = process.ExitCode;
info.ExitTime = process.ExitTime;
}
catch { }
onExited?.Invoke(sender, args);
(sender as IDisposable)?.Dispose();
};
// start the process
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
// return information
info.Process = process;
info.ID = process.Id;
info.StartTime = process.StartTime;
return info;
}
/// <summary>
/// Starts to run an external process directly
/// </summary>
/// <param name="filePath">The absolute path to the file of external process</param>
/// <param name="arguments">The arguments</param>
/// <param name="onExited">The action to run when the process was exited (Exited event)</param>
/// <param name="onDataReceived">The method to handle the data receive events (include OutputDataReceived and ErrorDataReceived events)</param>
/// <returns></returns>
/// <remarks>
/// Remember assign execution permisions to the file (sudo chmod 777 'filename') while running on Linux/macOS
/// </remarks>
public static Info Start(string filePath, string arguments, Action<object, EventArgs> onExited, Action<object, DataReceivedEventArgs> onDataReceived = null)
=> ExternalProcess.Start(filePath, arguments, null, onExited, onDataReceived, onDataReceived, false);
/// <summary>
/// Starts to run a command as external process with 'cmd.exe' (Windows) or '/bin/bash' (Linux/macOS)
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="workingDirectory">The working directory</param>
/// <param name="onExited">The action to run when the process was exited (Exited event)</param>
/// <param name="onOutputDataReceived">The action to run when an output message was received (OutputDataReceived event)</param>
/// <param name="onErrorDataReceived">The action to run when an error message was received (ErrorDataReceived event)</param>
/// <param name="captureOutput">true to capture output (standard output and error output) as string</param>
/// <returns></returns>
/// <remarks>
/// Remember assign execution permisions to the file (sudo chmod 777 'filename') while running on Linux/macOS
/// </remarks>
public static Info Start(string command, string workingDirectory = null, Action<object, EventArgs> onExited = null, Action<object, DataReceivedEventArgs> onOutputDataReceived = null, Action<object, DataReceivedEventArgs> onErrorDataReceived = null, bool captureOutput = false)
{
var arguments = RuntimeInformation.IsOSPlatform(OSPlatform.Windows)
? $"/c \"{command.Replace("\"", "\"\"\"")}\""
: $"-c \"{command.Replace("\"", "\\\"")}\"";
return ExternalProcess.Start(RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "cmd.exe" : "/bin/bash", arguments, workingDirectory, onExited, onOutputDataReceived, onErrorDataReceived, captureOutput);
}
/// <summary>
/// Starts to run a command as external process with 'cmd.exe' (Windows) or '/bin/bash' (Linux/macOS), wait for complete
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="workingDirectory">The working directory</param>
/// <param name="onExited">The action to run when the process was exited (Exited event)</param>
/// <param name="onOutputDataReceived">The action to run when an output message was received (OutputDataReceived event)</param>
/// <param name="onErrorDataReceived">The action to run when an error message was received (ErrorDataReceived event)</param>
/// <param name="captureOutput">true to capture output (standard output and error output) as string</param>
/// <returns></returns>
/// <remarks>
/// Remember assign execution permisions to the file (sudo chmod 777 'filename') while running on Linux/macOS
/// </remarks>
public static void Run(string command, string workingDirectory = null, Action<object, EventArgs> onExited = null, Action<object, DataReceivedEventArgs> onOutputDataReceived = null, Action<object, DataReceivedEventArgs> onErrorDataReceived = null, bool captureOutput = false)
{
var info = ExternalProcess.Start(command, workingDirectory, onExited, onOutputDataReceived, onErrorDataReceived, captureOutput);
info.Process.WaitForExit();
info.Stop();
}
#if !NETSTANDARD2_0
/// <summary>
/// Starts to run a command as external process with 'cmd.exe' (Windows) or '/bin/bash' (Linux/macOS) and wait for complete
/// </summary>
/// <param name="command">The command to run</param>
/// <param name="workingDirectory">The working directory</param>
/// <param name="onExited">The action to run when the process was exited (Exited event)</param>
/// <param name="onOutputDataReceived">The action to run when an output message was received (OutputDataReceived event)</param>
/// <param name="onErrorDataReceived">The action to run when an error message was received (ErrorDataReceived event)</param>
/// <param name="captureOutput">true to capture output (standard output and error output) as string</param>
/// <returns></returns>
/// <remarks>
/// Remember assign execution permisions to the file (sudo chmod 777 'filename') while running on Linux/macOS
/// </remarks>
public static async Task RunAsync(string command, string workingDirectory = null, Action<object, EventArgs> onExited = null, Action<object, DataReceivedEventArgs> onOutputDataReceived = null, Action<object, DataReceivedEventArgs> onErrorDataReceived = null, bool captureOutput = false, CancellationToken cancellationToken = default)
{
var info = ExternalProcess.Start(command, workingDirectory, onExited, onOutputDataReceived, onErrorDataReceived, captureOutput);
await info.Process.WaitForExitAsync(cancellationToken).ConfigureAwait(false);
info.Stop();
}
/// <summary>
/// Starts to run a command as external process with 'cmd.exe' (Windows) or '/bin/bash' (Linux/macOS) and wait for complete
/// </summary>
/// <param name="command">The command to run</param>
/// <returns></returns>
/// <remarks>
/// Remember assign execution permisions to the file (sudo chmod 777 'filename') while running on Linux/macOS
/// </remarks>
public static Task RunAsync(string command, CancellationToken cancellationToken)
=> ExternalProcess.RunAsync(command, null, null, null, null, false, cancellationToken);
#endif
/// <summary>
/// Stops an external process
/// </summary>
/// <param name="info">The information</param>
/// <param name="onCompleted">The action to run when completed</param>
/// <param name="onError">The action to run when got error</param>
/// <param name="waitingTimes">The time for waiting when try to close</param>
public static void Stop(Info info, Action<Info> onCompleted = null, Action<Exception> onError = null, int waitingTimes = 456)
{
if (info == null || info.Process == null)
try
{
info?.Process?.Dispose();
onCompleted?.Invoke(info);
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
else
try
{
ExternalProcess.Kill
(
info.Process,
process =>
{
process.StandardInput.WriteLine("exit");
process.StandardInput.Close();
process.WaitForExit(waitingTimes > 0 ? waitingTimes : 456);
process.Refresh();
},
process =>
{
try
{
process.WaitForExit(123);
info.ExitCode = process.ExitCode;
info.ExitTime = process.ExitTime;
}
catch (InvalidOperationException ex)
{
if (ex.Message.IsContains("No process is associated with this object"))
{
info.ExitCode = 0;
info.ExitTime = DateTime.Now;
}
else
onError?.Invoke(ex);
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
try
{
info.Process?.Dispose();
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
onCompleted?.Invoke(info);
},
onError
);
}
catch (Exception ex)
{
try
{
info.Process?.Kill();
info.Process?.Dispose();
onCompleted?.Invoke(info);
}
catch
{
onError?.Invoke(ex);
}
}
}
/// <summary>
/// Kills an external process
/// </summary>
/// <param name="process"></param>
/// <param name="tryToClose">The action to run to try to close the process before the process be killed</param>
/// <param name="onKilled">The action to run when process was killed</param>
/// <param name="onError">The action to run when got error</param>
public static void Kill(Process process, Action<Process> tryToClose = null, Action<Process> onKilled = null, Action<Exception> onError = null)
{
try
{
// check
if (process == null)
{
onKilled?.Invoke(process);
return;
}
// try to close
try
{
tryToClose?.Invoke(process);
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
// re-check after trying to close
try
{
process.WaitForExit(123);
if (process.HasExited)
{
onKilled?.Invoke(process);
return;
}
}
catch (InvalidOperationException ex)
{
if (ex.Message.IsContains("No process is associated with this object"))
{
onKilled?.Invoke(process);
return;
}
else
onError?.Invoke(ex);
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
// kill
if (process.StartInfo.RedirectStandardInput)
{
try
{
process.StandardInput.Close();
process.CloseMainWindow();
process.WaitForExit(456);
process.Refresh();
}
catch { }
if (!process.HasExited)
process.Kill();
}
else if (!process.HasExited)
process.Kill();
// callback
onKilled?.Invoke(process);
}
catch (Exception ex)
{
try
{
process?.Kill();
process?.Dispose();
onKilled?.Invoke(process);
}
catch
{
onError?.Invoke(ex);
}
}
}
/// <summary>
/// Kills an external process that specified by identity
/// </summary>
/// <param name="processID">The integer that presents the identity of a process that to be killed</param>
/// <param name="tryToClose">The action to try to close the process before the process be killed</param>
/// <param name="onKilled">The action to run when process was killed</param>
/// <param name="onError">The action to run when got error</param>
public static void Kill(int processID, Action<Process> tryToClose = null, Action<Process> onKilled = null, Action<Exception> onError = null)
{
try
{
using (var process = Process.GetProcessById(processID))
{
ExternalProcess.Kill(process, tryToClose, onKilled, onError);
}
}
catch (Exception ex)
{
onError?.Invoke(ex);
}
}
/// <summary>
/// Sends a command
/// </summary>
/// <param name="process"></param>
/// <param name="command"></param>
public static void Send(Process process, string command)
=> process.StandardInput.WriteLine(command);
/// <summary>
/// Sends a command
/// </summary>
/// <param name="process"></param>
/// <param name="command"></param>
/// <param name="cancellationToken"></param>
public static Task SendAsync(Process process, string command, CancellationToken cancellationToken = default)
=> process.StandardInput.WriteLineAsync(command, cancellationToken);
/// <summary>
/// Presents information of an external process
/// </summary>
public class Info
{
/// <summary>
/// Creates new information of an external process
/// </summary>
/// <param name="filePath">The absolute path to the file of external process</param>
/// <param name="arguments">The arguments</param>
public Info(string filePath = null, string arguments = null)
{
this.FilePath = filePath ?? "";
this.Arguments = arguments ?? "";
}
/// <summary>
/// Gest the absolute path of file
/// </summary>
public string FilePath { get; internal set; }
/// <summary>
/// Gets the arguments
/// </summary>
public string Arguments { get; internal set; }
/// <summary>
/// Ges the standard output (stdout)
/// </summary>
public string StandardOutput { get; internal set; } = "";
/// <summary>
/// Gets the standard error (stderr)
/// </summary>
public string StandardError { get; internal set; } = "";
/// <summary>
/// Gets the related process
/// </summary>
public Process Process { get; internal set; }
/// <summary>
/// Gets the identity
/// </summary>
public int? ID { get; internal set; }
/// <summary>
/// Gets the start time
/// </summary>
public DateTime? StartTime { get; internal set; }
/// <summary>
/// Gets the exit time
/// </summary>
public DateTime? ExitTime { get; internal set; }
/// <summary>
/// Gets the exit code
/// </summary>
public int? ExitCode { get; internal set; }
/// <summary>
/// Gets the extra information
/// </summary>
public Dictionary<string, object> Extra { get; } = new Dictionary<string, object>();
/// <summary>
/// Sets the value of a specified key of the extra information
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
public void Set<T>(string key, T value)
=> this.Extra[key] = value;
/// <summary>
/// Gets the value of a specified key from the extra information
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="default"></param>
/// <returns></returns>
public T Get<T>(string key, T @default = default)
=> this.Extra.TryGetValue(key, out object value) && value != null && value is T
? (T)value
: @default;
/// <summary>
/// Removes the value of a specified key from the extra information
/// </summary>
/// <param name="key"></param>
/// <returns></returns>
public bool Remove(string key)
=> this.Extra.Remove(key);
/// <summary>
/// Removes the value of a specified key from the extra information
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="key"></param>
/// <param name="value"></param>
/// <returns></returns>
public bool Remove<T>(string key, out T value)
{
value = this.Get<T>(key);
return this.Remove(key);
}
/// <summary>
/// Stops an external process
/// </summary>
/// <param name="onCompleted">The action to run when completed</param>
/// <param name="onError">The action to run when got error</param>
/// <param name="waitingTimes">The time for waiting when try to close</param>
public void Stop(Action<Info> onCompleted = null, Action<Exception> onError = null, int waitingTimes = 456)
=> ExternalProcess.Stop(this, onCompleted, onError, waitingTimes);
/// <summary>
/// Kills an external process
/// </summary>
/// <param name="tryToClose">The action to run to try to close the process before the process be killed</param>
/// <param name="onKilled">The action to run when process was killed</param>
/// <param name="onError">The action to run when got error</param>
public void Kill(Action<Process> tryToClose = null, Action<Process> onKilled = null, Action<Exception> onError = null)
=> ExternalProcess.Kill(this.Process, tryToClose, onKilled, onError);
/// <summary>
/// Sends a command
/// </summary>
/// <param name="command"></param>
public void Send(string command)
=> ExternalProcess.Send(this.Process, command);
/// <summary>
/// Sends a command
/// </summary>
/// <param name="command"></param>
public Task SendAsync(string command, CancellationToken cancellationToken = default)
=> ExternalProcess.SendAsync(this.Process, command, cancellationToken);
}
}
}