- Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathChildProcessExamplesWindows.cs
More file actions
Latest commit
186 lines (160 loc) · 6.9 KB
/
Copy pathChildProcessExamplesWindows.cs
File metadata and controls
186 lines (160 loc) · 6.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
// Copyright (c) @asmichi (https://github.com/asmichi). Licensed under the MIT License. See LICENCE in the project root for details.
usingSystem;
usingSystem.Collections.Generic;
usingSystem.Diagnostics;
usingSystem.IO;
usingSystem.IO.Pipes;
usingSystem.Text;
usingSystem.Threading.Tasks;
usingAsmichi.ProcessManagement;
#pragma warning disable CA1849// Call async methods when in an async method
// NOTE:
//
// When executing "cmd.exe", you need to set DisableArgumentQuoting and escape arguments on your own.
// You need to escape arguments in a way specific to the command being invoked.
// There is no standard quoting method possible for "cmd.exe".
//
// If arguments originate from an untrusted input, it may be a good idea to avoid executing "cmd.exe".
// Incorrectly escaped arguments can lead to execution of an arbitrary executable because "cmd.exe /c"
// takes an arbitrary shell command line.
//
// Search "BatBadBut vulnerability" for the background.
//
namespaceAsmichi
{
publicstaticclassChildProcessExamplesWindows
{
publicstaticasyncTaskRun()
{
WriteHeader(nameof(BasicAsync));
awaitBasicAsync();
WriteHeader(nameof(RedirectionToFileAsync));
awaitRedirectionToFileAsync();
WriteHeader(nameof(TruePipingAsync));
awaitTruePipingAsync();
WriteHeader(nameof(WaitForExitAsync));
awaitWaitForExitAsync();
}
privatestaticvoidWriteHeader(stringname)
{
Console.WriteLine();
Console.WriteLine("*** {0}",name);
}
privatestaticasyncTaskBasicAsync()
{
varsi=newChildProcessStartInfo("cmd","/C","echo","foo")
{
StdOutputRedirection=OutputRedirection.OutputPipe,
// Works like 2>&1
StdErrorRedirection=OutputRedirection.OutputPipe,
Flags=ChildProcessFlags.DisableArgumentQuoting,
};
usingvarp=ChildProcess.Start(si);
using(varsr=newStreamReader(p.StandardOutput))
{
// "foo"
Console.Write(awaitsr.ReadToEndAsync());
}
awaitp.WaitForExitAsync();
// ExitCode: 0
Console.WriteLine("ExitCode: {0}",p.ExitCode);
}
privatestaticasyncTaskRedirectionToFileAsync()
{
vartempFile=Path.GetTempFileName();
varsi=newChildProcessStartInfo("cmd","/C","set")
{
ExtraEnvironmentVariables=newDictionary<string,string>{{"A","A"}},
StdOutputRedirection=OutputRedirection.File,
StdErrorRedirection=OutputRedirection.File,
StdOutputFile=tempFile,
StdErrorFile=tempFile,
Flags=ChildProcessFlags.UseCustomCodePage|ChildProcessFlags.DisableArgumentQuoting,
CodePage=Encoding.Default.CodePage,// UTF-8 on .NET Core
};
using(varp=ChildProcess.Start(si))
{
awaitp.WaitForExitAsync();
}
// A=A
// ALLUSERSPROFILE=C:\ProgramData
// ...
Console.WriteLine(File.ReadAllText(tempFile));
File.Delete(tempFile);
}
// True piping: you can pipe the output of a child into another child without ever reading the output.
privatestaticasyncTaskTruePipingAsync()
{
// Create an anonymous pipe.
usingvarinPipe=newAnonymousPipeServerStream(PipeDirection.In);
varsi1=newChildProcessStartInfo("cmd","/C","set")
{
// Connect the output to writer side of the pipe.
StdOutputRedirection=OutputRedirection.Handle,
StdErrorRedirection=OutputRedirection.Handle,
StdOutputHandle=inPipe.ClientSafePipeHandle,
StdErrorHandle=inPipe.ClientSafePipeHandle,
Flags=ChildProcessFlags.UseCustomCodePage|ChildProcessFlags.DisableArgumentQuoting,
CodePage=Encoding.Default.CodePage,// UTF-8 on .NET Core
};
varsi2=newChildProcessStartInfo("findstr","Windows")
{
// Connect the input to the reader side of the pipe.
StdInputRedirection=InputRedirection.Handle,
StdInputHandle=inPipe.SafePipeHandle,
StdOutputRedirection=OutputRedirection.OutputPipe,
StdErrorRedirection=OutputRedirection.OutputPipe,
Flags=ChildProcessFlags.UseCustomCodePage,
CodePage=Encoding.Default.CodePage,// UTF-8 on .NET Core
};
usingvarp1=ChildProcess.Start(si1);
usingvarp2=ChildProcess.Start(si2);
// Close our copy of the pipe handles. (Otherwise p2 will get stuck while reading from the pipe.)
inPipe.DisposeLocalCopyOfClientHandle();
inPipe.Close();
using(varsr=newStreamReader(p2.StandardOutput))
{
// ...
// OS=Windows_NT
// ...
Console.Write(awaitsr.ReadToEndAsync());
}
awaitp1.WaitForExitAsync();
awaitp2.WaitForExitAsync();
}
// Truely asynchronous WaitForExitAsync: WaitForExitAsync does not consume a thread-pool thread.
// You will not need a dedicated thread for handling a child process.
// You can handle more processes than the number of threads.
privatestaticasyncTaskWaitForExitAsync()
{
constintN=128;
varstopWatch=Stopwatch.StartNew();
vartasks=newTask[N];
for(inti=0;i<N;i++)
{
tasks[i]=SpawnCmdAsync(i);
}
// Spawned 128 processes.
// ERROR: Timed out waiting for 'pause5'.
// (snip)
// ERROR: Timed out waiting for 'pause127'.
// The 128 processes have exited.
// Elapsed Time: 3262 ms
Console.WriteLine("Spawned {0} processes.",N);
awaitTask.WhenAll(tasks);
Console.WriteLine("The {0} processes have exited.",N);
Console.WriteLine("Elapsed Time: {0} ms",stopWatch.ElapsedMilliseconds);
staticasyncTaskSpawnCmdAsync(inti)
{
varsi=newChildProcessStartInfo("waitfor","/T","3",$"pause{i}")
{
StdInputRedirection=InputRedirection.ParentInput,
StdOutputRedirection=OutputRedirection.NullDevice,
Flags=ChildProcessFlags.AttachToCurrentConsole,
};
usingvarp=ChildProcess.Start(si);
awaitp.WaitForExitAsync();
}
}
}
}