forked from PowerShell/PowerShell
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathAsyncProcess.cs
More file actions
518 lines (441 loc) · 14.3 KB
/
Copy pathAsyncProcess.cs
File metadata and controls
518 lines (441 loc) · 14.3 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
//
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace Microsoft.PackageManagement.Internal.Utility.Platform {
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Threading;
using Collections;
using Extensions;
/// <summary>
/// This is a wrapper around the Process class to provide easy access to asynchronous
/// stdout/stderr streams.
/// TODO: add support for a cancellation token to kill the process when cancelled.
/// </summary>
internal class AsyncProcess : IDisposable {
protected Process _process;
private BlockingCollection<string> _stdError = new BlockingCollection<string>();
private ManualResetEvent _stdErrStarted = new ManualResetEvent(false);
private BlockingCollection<string> _stdOut = new BlockingCollection<string>();
private ManualResetEvent _stdOutStarted = new ManualResetEvent(false);
protected AsyncProcess(Process process) {
_process = process;
}
public IEnumerable<string> StandardError {
get {
_stdErrStarted.WaitOne();
return _stdError;
}
}
public IEnumerable<string> StandardOutput {
get {
_stdOutStarted.WaitOne();
return _stdOut;
}
}
public int ExitCode {
get {
return _process.ExitCode;
}
}
public bool HasExited {
get {
return _process.HasExited;
}
}
public DateTime ExitTime {
get {
return _process.ExitTime;
}
}
#if !CORECLR
public IntPtr Handle {
get {
return _process.Handle;
}
}
public int HandleCount {
get {
return _process.HandleCount;
}
}
public IntPtr MainWindowHandle
{
get
{
return _process.MainWindowHandle;
}
}
public string MainWindowTitle
{
get
{
return _process.MainWindowTitle;
}
}
public ISynchronizeInvoke SynchronizingObject
{
get
{
return _process.SynchronizingObject;
}
}
public bool Responding
{
get
{
return _process.Responding;
}
}
public bool WaitForInputIdle(int milliseconds)
{
return _process.WaitForInputIdle(milliseconds);
}
public bool WaitForInputIdle()
{
return WaitForInputIdle(-1);
}
public bool CloseMainWindow()
{
return _process.CloseMainWindow();
}
#endif
public void Close()
{
#if !CORECLR
_process.Close();
#else
Dispose();
#endif
}
public int Id {
get {
return _process.Id;
}
}
public string MachineName {
get {
return _process.MachineName;
}
}
public ProcessModule MainModule {
get {
return _process.MainModule;
}
}
public IntPtr MaxWorkingSet {
get {
return _process.MaxWorkingSet;
}
}
public IntPtr MinWorkingSet {
get {
return _process.MinWorkingSet;
}
}
public ProcessModuleCollection Modules {
get {
return _process.Modules;
}
}
public long NonpagedSystemMemorySize64 {
get {
return _process.NonpagedSystemMemorySize64;
}
}
public long PagedMemorySize64 {
get {
return _process.PagedMemorySize64;
}
}
public long PagedSystemMemorySize64 {
get {
return _process.PagedSystemMemorySize64;
}
}
public long PeakPagedMemorySize64 {
get {
return _process.PeakPagedMemorySize64;
}
}
public long PeakWorkingSet64 {
get {
return _process.PeakWorkingSet64;
}
}
public long PeakVirtualMemorySize64 {
get {
return _process.PeakVirtualMemorySize64;
}
}
public bool PriorityBoostEnabled {
get {
return _process.PriorityBoostEnabled;
}
set {
_process.PriorityBoostEnabled = value;
}
}
public ProcessPriorityClass PriorityClass {
get {
return _process.PriorityClass;
}
set {
_process.PriorityClass = value;
}
}
public long PrivateMemorySize64 {
get {
return _process.PrivateMemorySize64;
}
}
public TimeSpan PrivilegedProcessorTime {
get {
return _process.PrivilegedProcessorTime;
}
}
public string ProcessName {
get {
return _process.ProcessName;
}
}
public IntPtr ProcessorAffinity {
get {
return _process.ProcessorAffinity;
}
set {
_process.ProcessorAffinity = value;
}
}
public int SessionId {
get {
return _process.SessionId;
}
}
public DateTime StartTime {
get {
return _process.StartTime;
}
}
public ProcessThreadCollection Threads {
get {
return _process.Threads;
}
}
public TimeSpan TotalProcessorTime {
get {
return _process.TotalProcessorTime;
}
}
public TimeSpan UserProcessorTime {
get {
return _process.UserProcessorTime;
}
}
public long VirtualMemorySize64 {
get {
return _process.VirtualMemorySize64;
}
}
public bool EnableRaisingEvents {
get {
return _process.EnableRaisingEvents;
}
set {
_process.EnableRaisingEvents = value;
}
}
public long WorkingSet64 {
get {
return _process.WorkingSet64;
}
}
public void Dispose() {
Dispose(true);
GC.SuppressFinalize(this);
}
public static AsyncProcess Start(ProcessStartInfo startInfo) {
return Start(startInfo, null);
}
private void ErrorDataReceived(object sender, DataReceivedEventArgs args) {
_stdErrStarted.Set();
if (_stdError != null) {
_stdError.Add(args.Data ?? string.Empty);
} else {
Console.WriteLine("Attempting to add when collection is null!!!!! (stdErr)");
_process.ErrorDataReceived -= ErrorDataReceived;
}
}
private void OutputDataReceived(object sender, DataReceivedEventArgs args) {
_stdOutStarted.Set();
if (_stdOut != null) {
_stdOut.Add(args.Data ?? string.Empty);
} else {
Console.WriteLine("Attempting to add when collection is null!!!!! (stdOut)");
_process.OutputDataReceived -= OutputDataReceived;
}
}
private void ProcessExited(object sender, EventArgs args) {
WaitForExit();
_stdError.CompleteAdding();
_stdOut.CompleteAdding();
_stdErrStarted.Set();
_stdOutStarted.Set();
}
public static AsyncProcess Start(ProcessStartInfo startInfo, IDictionary environment) {
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
startInfo.UseShellExecute = false;
var redirecting = true;
#if !CORECLR
if (AdminPrivilege.IsElevated) {
startInfo.Verb = "";
} else {
if ("runas".EqualsIgnoreCase(startInfo.Verb)) {
redirecting = false;
startInfo.UseShellExecute = true;
startInfo.RedirectStandardError = false;
startInfo.RedirectStandardOutput = false;
}
}
#endif
if (environment != null) {
foreach (var i in environment.Keys) {
#if !CORECLR
startInfo.EnvironmentVariables[(string)i] = (string)environment[i];
#else
startInfo.Environment[(string)i] = (string)environment[i];
#endif
}
}
var result = new AsyncProcess(new Process {
StartInfo = startInfo
});
result._process.EnableRaisingEvents = true;
// set up std* access
if (redirecting) {
result._process.ErrorDataReceived += result.ErrorDataReceived;
result._process.OutputDataReceived += result.OutputDataReceived;
}
result._process.Exited += result.ProcessExited;
result._process.Start();
if (redirecting) {
result._process.BeginErrorReadLine();
result._process.BeginOutputReadLine();
}
return result;
}
public static AsyncProcess Start(string fileName) {
return Start(new ProcessStartInfo {
FileName = fileName
});
}
public static AsyncProcess Start(string fileName, IDictionary environment) {
return Start(new ProcessStartInfo {
FileName = fileName
}, environment);
}
public static AsyncProcess Start(string fileName, string parameters, IDictionary environment) {
return Start(new ProcessStartInfo {
FileName = fileName,
Arguments = parameters
}, environment);
}
public static AsyncProcess Start(string fileName, string parameters) {
return Start(new ProcessStartInfo {
FileName = fileName,
Arguments = parameters
});
}
public void Kill() {
_process.Kill();
}
public bool WaitForExit(int milliseconds) {
return _process.WaitForExit(milliseconds);
}
public void WaitForExit() {
WaitForExit(-1);
}
public event EventHandler Exited {
add {
_process.Exited += value;
}
remove {
_process.Exited -= value;
}
}
protected virtual void Dispose(bool disposing) {
if (disposing) {
if (_process != null) {
if (!_process.HasExited) {
// this object is being disposed, yet the process isn't finished.
Console.WriteLine("Killing AsyncProcess");
_process.Kill();
}
((IDisposable)_process).Dispose();
}
_process = null;
if (_stdOut != null) {
((IDisposable)_stdOut).Dispose();
}
_stdOut = null;
if (_stdError != null) {
((IDisposable)_stdError).Dispose();
}
_stdError = null;
if (_stdOutStarted != null) {
_stdOutStarted.Dispose();
}
_stdOutStarted = null;
if (_stdErrStarted != null) {
_stdErrStarted.Dispose();
}
_stdErrStarted = null;
}
}
public static void EnterDebugMode() {
Process.EnterDebugMode();
}
public static void LeaveDebugMode() {
Process.LeaveDebugMode();
}
public static AsyncProcess GetProcessById(int processId, string machineName) {
return new AsyncProcess(Process.GetProcessById(processId, machineName));
}
public static AsyncProcess GetProcessById(int processId) {
return new AsyncProcess(Process.GetProcessById(processId));
}
public static AsyncProcess[] GetProcessesByName(string processName) {
return Process.GetProcessesByName(processName).Select(each => new AsyncProcess(each)).ToArray();
}
public static AsyncProcess[] GetProcessesByName(string processName, string machineName) {
return Process.GetProcessesByName(processName, machineName).Select(each => new AsyncProcess(each)).ToArray();
}
public static AsyncProcess[] GetProcesses() {
return Process.GetProcesses().Select(each => new AsyncProcess(each)).ToArray();
}
public static AsyncProcess[] GetProcesses(string machineName) {
return Process.GetProcesses(machineName).Select(each => new AsyncProcess(each)).ToArray();
}
public static AsyncProcess GetCurrentProcess() {
return new AsyncProcess(Process.GetCurrentProcess());
}
public void Refresh() {
_process.Refresh();
}
}
}