forked from florentbr/SeleniumBasic
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProcessExt.cs
More file actions
560 lines (451 loc) · 20.4 KB
/
ProcessExt.cs
File metadata and controls
560 lines (451 loc) · 20.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
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
using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Text;
namespace Selenium.Internal {
public class ProcessExt : IDisposable {
#region Standard Environemnt Variables
static readonly string[] STD_ENV_VARS = {
"ALLUSERSPROFILE","APPDATA","COMPUTERNAME","ComSpec","CommonProgramFiles",
"CommonProgramFiles(x86)","CommonProgramW6432","HOMEDRIVE","HOMEPATH",
"LOCALAPPDATA","LOGONSERVER","NUMBER_OF_PROCESSORS","OS","PATHEXT",
"PROCESSOR_ARCHITECTURE","PROCESSOR_ARCHITEW6432","PROCESSOR_IDENTIFIER",
"PROCESSOR_LEVEL","PROCESSOR_REVISION","PUBLIC","ProgramData","ProgramFiles",
"ProgramFiles(x86)","ProgramW6432","SystemDrive","SystemRoot","TEMP","TMP",
"USERDOMAIN","USERDOMAIN_ROAMINGPROFILE","USERNAME","USERPROFILE","WINDIR",
"JAVA_HOME"
};
#endregion
/// <summary>
/// Starts a process
/// </summary>
/// <param name="filepath">File path</param>
/// <param name="args">Arguments</param>
/// <param name="dir">Working dir. Inherits the current directory if null</param>
/// <param name="env">Environement variables. Inherits all of them if null</param>
/// <param name="noWindow">Hides the window if true</param>
/// <param name="createJob">Creates a Job if true</param>
/// <returns></returns>
public static ProcessExt Start(string filepath, IEnumerable args
, string dir, Hashtable env, bool noWindow, bool createJob) {
string cmd = ProcessExt.BuildCommandLine(filepath, args);
StringBuilder envVars = BuildEnvironmentVars(env);
var si = new Native.STARTUPINFO();
var pi = new Native.PROCESS_INFORMATION();
int createFlags = Native.CREATE_UNICODE_ENVIRONMENT;
if (noWindow)
createFlags |= Native.CREATE_NO_WINDOW;
IntPtr hJob = IntPtr.Zero;
bool success = false;
if (createJob) {
IntPtr curProc = Native.GetCurrentProcess();
bool isProcessInJob = false;
success = Native.IsProcessInJob(curProc, IntPtr.Zero, out isProcessInJob);
Native.CloseHandle(curProc);
if (success) {
int createFlagsJob = createFlags | Native.CREATE_SUSPENDED;
if (isProcessInJob)
createFlagsJob |= Native.CREATE_BREAKAWAY_FROM_JOB;
success = Native.CreateProcess(null
, cmd
, IntPtr.Zero
, IntPtr.Zero
, false
, createFlagsJob
, envVars
, dir, si, pi);
if (success) {
success = AssignProcessToNewJob(pi.hProcess, null, out hJob);
if (success) {
if (-1 == Native.ResumeThread(pi.hThread))
throw new Win32Exception();
} else {
Native.TerminateProcess(pi.hProcess, -1);
Native.CloseHandle(pi.hProcess);
Native.CloseHandle(pi.hThread);
Native.CloseHandle(hJob);
hJob = IntPtr.Zero;
}
}
}
}
if (!success) {
success = Native.CreateProcess(null
, cmd
, IntPtr.Zero
, IntPtr.Zero
, false
, createFlags
, envVars
, dir, si, pi);
if (!success)
throw new Win32Exception();
}
return new ProcessExt(pi.dwProcessId, pi.hProcess, hJob);
}
/// <summary>
/// Execute a command line.
/// </summary>
/// <param name="cmd">Command line</param>
/// <param name="dir">Working dir. Inherits the current directory if null.</param>
/// <param name="env">Environement variables. Inherits all of them if null.</param>
/// <param name="noWindow">Hides the window if true</param>
public static void Execute(string cmd, string dir
, Hashtable env = null, bool noWindow = false) {
var si = new Native.STARTUPINFO();
var pi = new Native.PROCESS_INFORMATION();
int createFlags = Native.CREATE_UNICODE_ENVIRONMENT;
if (noWindow)
createFlags |= Native.CREATE_NO_WINDOW;
StringBuilder envVars = BuildEnvironmentVars(env);
try {
bool success = Native.CreateProcess(null
, cmd
, IntPtr.Zero
, IntPtr.Zero
, false
, createFlags
, envVars
, dir, si, pi);
if (!success)
throw new Win32Exception();
} finally {
Native.CloseHandle(pi.hThread);
Native.CloseHandle(pi.hProcess);
}
}
/// <summary>
/// Returns all the standards environement variables.
/// </summary>
/// <returns></returns>
public static Hashtable GetStdEnvironmentVariables() {
IDictionary dict = Environment.GetEnvironmentVariables();
Hashtable newDict = new Hashtable(StringComparer.InvariantCultureIgnoreCase);
foreach (string key in STD_ENV_VARS) {
object value = dict[key];
if (value != null)
newDict.Add(key, (string)value);
}
return newDict;
}
[DebuggerDisplay("Pid:{Id} ParentPid:{ParentId}")]
public class ProcessRelationship {
public int Pid;
public int ParentPid;
}
/// <summary>
/// Returns all the process relationships.
/// </summary>
/// <returns></returns>
public static unsafe ProcessRelationship[] GetProcessRelationships() {
var relationchips = new List<ProcessRelationship>(100);
IntPtr snapshot = Native.CreateToolhelp32Snapshot(Native.TH32CS_SNAPPROCESS, 0);
int bufferSize = sizeof(Native.WinProcessEntry);
IntPtr buffer = Marshal.AllocHGlobal(bufferSize);
Marshal.WriteInt32(buffer, bufferSize);
var natEntryPtr = (Native.WinProcessEntry*)buffer;
try {
if (!Native.Process32First(snapshot, buffer))
throw new Win32Exception();
do {
Native.WinProcessEntry natEntry = *natEntryPtr;
ProcessRelationship relationchip = new ProcessRelationship();
relationchip.Pid = natEntry.th32ProcessID;
relationchip.ParentPid = natEntry.th32ParentProcessID;
relationchips.Add(relationchip);
} while (Native.Process32Next(snapshot, buffer));
} finally {
Marshal.FreeHGlobal(buffer);
Native.CloseHandle(snapshot);
}
return relationchips.ToArray();
}
#region Instance
private int _pid;
private IntPtr _hJob;
private IntPtr _hProcess;
// Summary:
// Initializes a new instance of the System.Diagnostics.Process class.
private ProcessExt(int pid, IntPtr hProcess, IntPtr hJob) {
_pid = pid;
_hJob = hJob;
_hProcess = hProcess;
}
/// <summary>
/// Release the resources
/// </summary>
public void Dispose() {
if (_hJob != IntPtr.Zero) {
Native.CloseHandle(_hJob);
_hJob = IntPtr.Zero;
}
if (_hProcess != IntPtr.Zero) {
Native.CloseHandle(_hProcess);
_hProcess = IntPtr.Zero;
}
_pid = 0;
}
/// <summary>
/// Process id
/// </summary>
public int Id {
get {
return _pid;
}
}
/// <summary>
/// Immediately stops the associated process and children processes.
/// </summary>
public void Kill() {
if (_hProcess == IntPtr.Zero)
return;
if (_hJob == IntPtr.Zero || !Native.TerminateJobObject(_hJob, -1)) {
ProcessRelationship[] relationships = GetProcessRelationships();
TerminateProcessTree(_pid, relationships);
}
}
/// <summary>
/// Waits the specified number of milliseconds for the associated process to exit.
/// </summary>
/// <param name="milliseconds">Amount of time, in milliseconds</param>
/// <returns>True if the associated process has exited, false otherwise</returns>
public bool WaitForExit(int milliseconds = -1) {
if (_hProcess == IntPtr.Zero)
return true;
int ret = Native.WaitForSingleObject(_hProcess, milliseconds);
if (ret == unchecked((int)0xFFFFFFFF)) // == WAIT_FAILED
throw new Win32Exception();
if (ret == 0x00000102L) // == WAIT_TIMEOUT
return false;
return true;
}
public int GetExitCode() {
if (_hProcess == IntPtr.Zero)
return 0;
int code;
if (!Native.GetExitCodeProcess(_hProcess, out code))
throw new Win32Exception();
return code;
}
/// <summary>
/// Gets a value indicating whether the associated process has been terminated.
/// </summary>
public bool HasExited {
get {
return this.WaitForExit(0);
}
}
#endregion
#region Support
private static string BuildCommandLine(string filepath, IEnumerable args) {
var cmd = new StringBuilder();
cmd.Append('"').Append(filepath.Trim('"')).Append('"');
foreach (string arg in args)
cmd.Append(' ').Append(arg);
return cmd.ToString();
}
/// <summary>
/// Assign a process to a new Job.
/// </summary>
/// <param name="hProcess">Process handle</param>
/// <param name="name">Optional - Job name</param>
/// <returns>Job handle or IntPtr.Zero if failed</returns>
private static bool AssignProcessToNewJob(IntPtr hProcess, string name, out IntPtr hJob) {
//Create a new Job
hJob = Native.CreateJobObject(IntPtr.Zero, name);
if (hJob == IntPtr.Zero)
return false;
var jeli = new Native.JOBOBJECT_EXTENDED_LIMIT_INFORMATION();
jeli.BasicLimitInformation.LimitFlags = Native.JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
jeli.BasicLimitInformation.LimitFlags |= Native.JOB_OBJECT_LIMIT_BREAKAWAY_OK;
bool success = Native.SetInformationJobObject(hJob
, Native.JOB_EXTENDED_LIMIT_INFORMATION
, ref jeli
, Native.JOBOBJECT_EXTENDED_LIMIT_INFORMATION.SIZE);
//Assign the process to the Job
if (!success || !Native.AssignProcessToJobObject(hJob, hProcess)) {
Native.CloseHandle(hJob);
hJob = IntPtr.Zero;
return false;
}
return true;
}
private static StringBuilder BuildEnvironmentVars(Hashtable dict) {
if (dict == null)
return null;
string[] keys = new string[dict.Count];
string[] values = new string[dict.Count];
dict.Keys.CopyTo(keys, 0);
dict.Values.CopyTo(values, 0);
Array.Sort(keys, values, CaseInsensitiveComparer.Default);
StringBuilder sb = new StringBuilder(800);
for (int i = 0; i < dict.Count; ++i) {
sb.Append(keys[i]);
sb.Append('=');
sb.Append(values[i]);
sb.Append('\0');
}
return sb;
}
private static void TerminateProcessTree(int pid, ProcessRelationship[] relationchips) {
if (pid == 0)
return;
//terminate childs recursively
for (int i = relationchips.Length; i-- > 0; ) {
ProcessRelationship relationchip = relationchips[i];
if (relationchip.ParentPid == pid) {
relationchip.ParentPid = 0;
TerminateProcessTree(relationchip.Pid, relationchips);
}
}
//terminate the process
IntPtr procHandle = Native.OpenProcess(Native.PROCESS_ALL_ACCESS, false, pid);
if (procHandle != IntPtr.Zero) {
try {
Native.TerminateProcess(procHandle, -1);
} catch {
} finally {
Native.CloseHandle(procHandle);
}
}
}
class Native {
const string KERNEL32 = "kernel32.dll";
const string USER32 = "user32.dll";
public const int JOB_OBJECT_LIMIT_BREAKAWAY_OK = 0x00000800;
public const int JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE = 0x00002000;
public const int JOB_EXTENDED_LIMIT_INFORMATION = 9;
public const int CREATE_SUSPENDED = 0x00000004;
public const int CREATE_NO_WINDOW = 0x08000000;
public const int CREATE_UNICODE_ENVIRONMENT = 0x00000400;
public const int CREATE_BREAKAWAY_FROM_JOB = 0x01000000;
public const int PROCESS_ALL_ACCESS = 0x001f0fff;
public const int TH32CS_SNAPPROCESS = 0x00000002;
public const int STARTF_USESHOWWINDOW = 0x00000001;
public const short SW_SHOWNOACTIVATE = 0x00000004;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)]
public unsafe struct WinProcessEntry {
public int dwSize;
public int cntUsage;
public int th32ProcessID;
public IntPtr th32DefaultHeapID;
public int th32ModuleID;
public int cntThreads;
public int th32ParentProcessID;
public int pcPriClassBase;
public int dwFlags;
public fixed byte fileName[260];
}
[StructLayout(LayoutKind.Sequential)]
public class STARTUPINFO {
public int cb = Marshal.SizeOf(typeof(STARTUPINFO));
public IntPtr lpReserved = IntPtr.Zero;
public IntPtr lpDesktop = IntPtr.Zero;
public IntPtr lpTitle = IntPtr.Zero;
public int dwX = 0;
public int dwY = 0;
public int dwXSize = 0;
public int dwYSize = 0;
public int dwXCountChars = 0;
public int dwYCountChars = 0;
public int dwFillAttribute = 0;
public int dwFlags = 0;
public short wShowWindow = 0;
public short cbReserved2 = 0;
public IntPtr lpReserved2 = IntPtr.Zero;
public IntPtr hStdInput = IntPtr.Zero;
public IntPtr hStdOutput = IntPtr.Zero;
public IntPtr hStdError = IntPtr.Zero;
}
[StructLayout(LayoutKind.Sequential)]
public class PROCESS_INFORMATION {
public IntPtr hProcess = IntPtr.Zero;
public IntPtr hThread = IntPtr.Zero;
public int dwProcessId = 0;
public int dwThreadId = 0;
}
[DllImport(KERNEL32, CharSet = CharSet.Auto, SetLastError = true, BestFitMapping = false)]
public static extern bool CreateProcess(
[MarshalAs(UnmanagedType.LPTStr)]
string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
int dwCreationFlags,
[MarshalAs(UnmanagedType.LPWStr)]
StringBuilder lpEnvironment,
[MarshalAs(UnmanagedType.LPTStr)]
string lpCurrentDirectory,
STARTUPINFO lpStartupInfo,
PROCESS_INFORMATION lpProcessInformation
);
[StructLayout(LayoutKind.Sequential)]
public struct IO_COUNTERS {
public UInt64 ReadOperationCount;
public UInt64 WriteOperationCount;
public UInt64 OtherOperationCount;
public UInt64 ReadTransferCount;
public UInt64 WriteTransferCount;
public UInt64 OtherTransferCount;
}
[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
public static int SIZE = Marshal.SizeOf(typeof(JOBOBJECT_EXTENDED_LIMIT_INFORMATION));
public JOBOBJECT_BASIC_LIMIT_INFORMATION BasicLimitInformation;
public IO_COUNTERS IoInfo;
public UIntPtr ProcessMemoryLimit;
public UIntPtr JobMemoryLimit;
public UIntPtr PeakProcessMemoryUsed;
public UIntPtr PeakJobMemoryUsed;
}
[StructLayout(LayoutKind.Sequential)]
public struct JOBOBJECT_BASIC_LIMIT_INFORMATION {
public Int64 PerProcessUserTimeLimit;
public Int64 PerJobUserTimeLimit;
public UInt32 LimitFlags;
public UIntPtr MinimumWorkingSetSize;
public UIntPtr MaximumWorkingSetSize;
public UInt32 ActiveProcessLimit;
public UIntPtr Affinity;
public UInt32 PriorityClass;
public UInt32 SchedulingClass;
}
[DllImport(KERNEL32, SetLastError = false)]
public static extern IntPtr GetCurrentProcess();
[DllImport(KERNEL32, SetLastError = false)]
public static extern bool IsProcessInJob(IntPtr Process, IntPtr Job, out bool Result);
[DllImport(KERNEL32, SetLastError = false, CharSet = CharSet.Ansi)]
public static extern IntPtr CreateJobObject(IntPtr a, string lpName);
[DllImport(KERNEL32, SetLastError = false)]
public static extern bool SetInformationJobObject(IntPtr hJob, int infoType
, ref JOBOBJECT_EXTENDED_LIMIT_INFORMATION lpJobObjectInfo, int cbJobObjectInfoLength);
[DllImport(KERNEL32, SetLastError = false)]
public static extern bool AssignProcessToJobObject(IntPtr job, IntPtr process);
[DllImport(KERNEL32, SetLastError = false)]
public static extern bool TerminateJobObject(IntPtr processHandle, int exitCode);
[DllImport(KERNEL32)]
public static extern IntPtr OpenProcess(int access, bool inherit, int processId);
[DllImport(KERNEL32)]
public static extern bool TerminateProcess(IntPtr processHandle, int exitCode);
[DllImport(KERNEL32, SetLastError = true)]
public static extern int ResumeThread(IntPtr hObject);
[DllImport(KERNEL32, SetLastError = true)]
public static extern bool CloseHandle(IntPtr hObject);
[DllImport(KERNEL32, SetLastError = true, ExactSpelling = true)]
public static extern int WaitForSingleObject(IntPtr hHandle, int dwMilliseconds);
[DllImport(KERNEL32, SetLastError = true)]
public static extern bool GetExitCodeProcess(IntPtr hProcess, out int lpExitCode);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern IntPtr CreateToolhelp32Snapshot(int flags, int processId);
[DllImport(KERNEL32, SetLastError = true, CharSet = CharSet.Ansi)]
public static extern bool Process32First(IntPtr handle, IntPtr entry);
[DllImport(KERNEL32, CharSet = CharSet.Ansi)]
public static extern bool Process32Next(IntPtr handle, IntPtr entry);
}
#endregion
}
}