子プロセスの標準入力のリダイレクトと標準出力・標準エラーのリダイレクトは同時に組み合わせることもできます。 これにより、子プロセスの標準入力に書き込み、子プロセスで何らかの処理を行った結果を標準出力から読み込む、さらに子プロセスの標準エラー出力も読み込む、といったことができます。
parent.exe:子プロセスの標準入出力へ読み書きする
Imports System
Imports System.Diagnostics
Imports System.IO
Class Sample
Shared Sub Main()
' 子プロセスchild.exeの起動オプション
Dim psi As New ProcessStartInfo("child.exe")
' シェルを使用せず子プロセスを起動する
' (リダイレクトするために必要)
' ⚠.NET Core/.NET 5以降ではデフォルトでFalseとなっている
psi.UseShellExecute = False
' 起動した子プロセスの標準入出力をリダイレクトする
psi.RedirectStandardInput = True
psi.RedirectStandardOutput = True
' 子プロセスを起動する
Using child As Process = Process.Start(psi)
Dim output As String = Nothing
' リダイレクトされた子プロセスの標準入出力を取得する
Using stdin As StreamWriter = child.StandardInput, _
stdout As StreamReader = child.StandardOutput
' 子プロセスの標準入力に書き込む
stdin.WriteLine("hello, world!")
' 子プロセスの標準出力から読み込む
output = stdout.ReadLine()
End Using ' 子プロセスの標準入出力を閉じて読み書きを終了する
' 子プロセスの終了を待機する
child.WaitForExit()
' 読み込んだテキストを表示する
Console.WriteLine($"output: ""{output}""")
End Using
End Sub
End Class
child.exe:標準入力から読み込み標準出力へ書き込む
Imports System
Class Sample
Shared Sub Main()
' 標準入力から読み込む
Dim line As String = Console.ReadLine()
' 標準出力へ書き込む
Console.WriteLine(line.ToUpper()) ' 入力を大文字化して出力
End Sub
End Class
実行結果
>parent.exe
output: "HELLO, WORLD!"
さらに、自プロセスの標準ストリームの入出力先を子プロセスの標準ストリームへリダイレクトすることにより、子プロセスの標準ストリームとパイプすることもできます。