-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathProcessHelper.cs
More file actions
382 lines (315 loc) · 12.4 KB
/
ProcessHelper.cs
File metadata and controls
382 lines (315 loc) · 12.4 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
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace RegExpressLibrary
{
public enum EncodingEnum
{
None,
ASCII,
UTF8,
Unicode,
}
public sealed class ProcessHelper : IDisposable
{
static readonly Encoding Utf8Encoding = new UTF8Encoding( encoderShouldEmitUTF8Identifier: false );
static readonly Encoding UnicodeEncoding = new UnicodeEncoding( bigEndian: false, byteOrderMark: false, throwOnInvalidBytes: true );
readonly string FileName;
bool ProcessExecuted = false;
readonly MemoryStream OutputMemoryStream = new( );
string? ErrorContents = null;
BinaryReader? BinaryReaderObj = null;
StreamReader? StreamReaderObj = null;
Stream? OutputStreamObj = null;
public EncodingEnum InputEncoding { get; set; } = EncodingEnum.None;
public EncodingEnum OutputEncoding { get; set; } = EncodingEnum.None;
public EncodingEnum ErrorEncoding { get; set; } = EncodingEnum.None;
public EncodingEnum AllEncoding
{
set
{
InputEncoding = OutputEncoding = ErrorEncoding = value;
}
}
public Action<BinaryWriter>? BinaryWriter { get; set; } = null;
public Action<StreamWriter>? StreamWriter { get; set; } = null;
public string[]? Arguments { get; set; } = null;
public Dictionary<string, string> Environment { get; } = [];
public string? WorkingDirectory { get; set; } = null;
public ProcessHelper( string fileName )
{
if( string.IsNullOrWhiteSpace( fileName ) ) throw new ArgumentException( nameof( fileName ) );
FileName = fileName;
}
public bool Start( ICancellable cnc )
{
if( BinaryWriter != null && StreamWriter != null ) throw new InvalidOperationException( "Binary Writer and Stream Writer cannot be both set." );
if( ( BinaryWriter != null || StreamWriter != null ) && InputEncoding == EncodingEnum.None ) throw new InvalidOperationException( "Input Encoding was not set." );
ProcessExecuted = false;
OutputMemoryStream.SetLength( 0 );
ErrorContents = null;
using Process p = new( );
if( Arguments != null )
{
foreach( var arg in Arguments )
{
p.StartInfo.ArgumentList.Add( arg );
}
}
p.StartInfo.CreateNoWindow = true;
//p.StartInfo.Domain
foreach( var kvp in Environment ) p.StartInfo.Environment.Add( kvp.Key, kvp.Value );
//p.StartInfo.EnvironmentVariables
p.StartInfo.ErrorDialog = false;
//p.StartInfo.ErrorDialogParentHandle
p.StartInfo.FileName = FileName;
//p.StartInfo.LoadUserProfile
//p.StartInfo.Password
//p.StartInfo.PasswordInClearText
p.StartInfo.RedirectStandardError = true;
p.StartInfo.RedirectStandardInput = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.StandardErrorEncoding = ErrorEncoding == EncodingEnum.None ? Encoding.ASCII : GetEncoding( ErrorEncoding );
p.StartInfo.StandardInputEncoding = InputEncoding == EncodingEnum.None ? Encoding.ASCII : GetEncoding( InputEncoding );
p.StartInfo.StandardOutputEncoding = OutputEncoding == EncodingEnum.None ? Encoding.ASCII : GetEncoding( OutputEncoding );
//p.StartInfo.UserName
p.StartInfo.UseShellExecute = false;
//p.StartInfo.Verb
//p.StartInfo.Verbs
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.StartInfo.WorkingDirectory = WorkingDirectory;
StringBuilder sb_errors = new( );
p.ErrorDataReceived += ( s, a ) =>
{
sb_errors.AppendLine( a.Data );
};
p.Start( );
p.BeginErrorReadLine( );
Thread? writing_thread = null;
if( BinaryWriter != null )
{
Debug.Assert( writing_thread == null );
writing_thread = new Thread( ( ) =>
{
try
{
using( BinaryWriter bw = new( p.StandardInput.BaseStream, GetEncoding( InputEncoding ), leaveOpen: false ) )
{
BinaryWriter( bw );
}
}
catch( Exception exc )
{
_ = exc;
if (InternalConfig.HandleException( exc ))
throw;
}
} )
{
Name = "rxStdinWriting",
IsBackground = true
};
writing_thread.Start( );
}
if( StreamWriter != null )
{
Debug.Assert( writing_thread == null );
writing_thread = new Thread( ( ) =>
{
try
{
using( StreamWriter sw = new( p.StandardInput.BaseStream, GetEncoding( InputEncoding ), leaveOpen: false ) )
{
StreamWriter( sw );
}
}
catch( Exception exc )
{
_ = exc;
if (InternalConfig.HandleException( exc ))
throw;
}
} )
{
Name = "rxStdinWriting",
IsBackground = true
};
writing_thread.Start( );
}
Thread reading_thread = new Thread( ( ) =>
{
try
{
p.StandardOutput.BaseStream.CopyTo( OutputMemoryStream );
}
catch( Exception exc )
{
_ = exc;
if (InternalConfig.HandleException( exc ))
throw;
}
} )
{
Name = "rxStdoutReading",
IsBackground = true
};
reading_thread.Start( );
bool cancel = false;
bool done = false;
for(; ; )
{
cancel = cnc.IsCancellationRequested;
if( cancel ) break;
done = p.WaitForExit( 444 );
if( done )
{
// another 'WaitForExit' required to finish the processing of streams;
// see: https://stackoverflow.com/questions/9533070/how-to-read-to-end-process-output-asynchronously-in-c,
// https://docs.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexit
p.WaitForExit( );
break;
}
}
//#if DEBUG
// if( p.WaitForExit( 0 ) ) Debug.WriteLine( $"Exit code: {p.ExitCode} -- {FileName}" );
//#endif
if( writing_thread != null ) StopThread( writing_thread );
StopThread( reading_thread );
if( cancel )
{
try
{
p.Kill( );
}
catch( Exception exc )
{
if( unchecked((uint)exc.HResult) != 0x80004005 && // 'E_ACCESSDENIED'
unchecked((uint)exc.HResult) != 0x80131509 ) // -2146233079, "Cannot process request because the process (<PID>) has exited."
{
if (InternalConfig.HandleException( exc ))
throw;
}
// ignore
}
return false;
}
Debug.Assert( done );
ErrorContents = sb_errors.ToString( );
ProcessExecuted = true;
return !cnc.IsCancellationRequested;
}
public BinaryReader BinaryReader
{
get
{
if( BinaryReaderObj == null )
{
if( !ProcessExecuted ) throw new InvalidOperationException( "Process not executed" );
if( StreamReaderObj != null || OutputStreamObj != null ) throw new InvalidOperationException( "Output already got." );
OutputMemoryStream.Position = 0;
BinaryReaderObj = new BinaryReader( OutputMemoryStream, GetEncoding( OutputEncoding ), leaveOpen: false );
}
return BinaryReaderObj;
}
}
public StreamReader StreamReader
{
get
{
if( StreamReaderObj == null )
{
if( !ProcessExecuted ) throw new InvalidOperationException( "Process not executed" );
if( BinaryReaderObj != null || OutputStreamObj != null ) throw new InvalidOperationException( "Output already got." );
OutputMemoryStream.Position = 0;
StreamReaderObj = new StreamReader( OutputMemoryStream, GetEncoding( OutputEncoding ), leaveOpen: false );
}
return StreamReaderObj;
}
}
public Stream OutputStream
{
get
{
if( OutputStreamObj == null )
{
if( !ProcessExecuted ) throw new InvalidOperationException( "Process not executed" );
if( BinaryReaderObj != null || StreamReaderObj != null ) throw new InvalidOperationException( "Output already got." );
OutputMemoryStream.Position = 0;
OutputStreamObj = OutputMemoryStream;
}
return OutputStreamObj;
}
}
public string? Error
{
get
{
if( !ProcessExecuted ) throw new InvalidOperationException( "Process not executed" );
return ErrorContents;
}
}
static void StopThread( Thread thread )
{
try
{
if( !thread.Join( 11 ) ) thread.Interrupt( );
// NOT SUPPORTED: if( !thread.Join( 11 ) ) thread.Abort( );
thread.Join( 11 );
}
catch( Exception exc )
{
_ = exc;
//?
// ignore
}
}
static Encoding GetEncoding( EncodingEnum encoding )
{
switch( encoding )
{
case EncodingEnum.None: throw new InvalidOperationException( $"Encoding not specified" );
case EncodingEnum.ASCII: return Encoding.ASCII;
case EncodingEnum.UTF8: return Utf8Encoding;
case EncodingEnum.Unicode: return UnicodeEncoding;
default:
throw new NotSupportedException( $"Encoding not supported: {encoding}" );
}
}
#region IDisposable
private bool disposedValue;
private void Dispose( bool disposing )
{
if( !disposedValue )
{
if( disposing )
{
// TODO: dispose managed state (managed objects)
OutputMemoryStream?.Dispose( );
BinaryReaderObj?.Dispose( );
StreamReaderObj?.Dispose( );
}
// TODO: free unmanaged resources (unmanaged objects) and override finalizer
// TODO: set large fields to null
disposedValue = true;
}
}
// // TODO: override finalizer only if 'Dispose(bool disposing)' has code to free unmanaged resources
// ~ProcessHelper()
// {
// // Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
// Dispose(disposing: false);
// }
public void Dispose( )
{
// Do not change this code. Put cleanup code in 'Dispose(bool disposing)' method
Dispose( disposing: true );
GC.SuppressFinalize( this );
}
#endregion IDisposable
}
}