我很难解读有关Process.StandardOutpout的MSDN文档,以了解Read(Char [],Int32,Int32)方法是否阻塞。我的理解是它不应该阻塞,但是当我将RedirectStandardInput设置为true时它似乎就是这样。
有没有人有这方面的经验;或者对我遇到的问题有一些解释?
这里的上下文是我不想等待整行(即使用行终止符),或者在读取标准输出之前退出进程。另外我不想使用回调。 我希望在进程写入时同步读取StdOut。
以下是我的代码的简化版本:
string command = @"C:\flex_sdks\flex_sdk_4.5.1.21328\bin\fcsh.exe";
Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardInput = false; # <-- if I set this to true, then
# the program hangs on
# p.StandardOutput.Read later on
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.FileName = command;
p.Start();
StringBuilder sb_stdout = new StringBuilder(1024);
char[] buffer = new char[64];
int nb_bytes_read;
while (true) {
do {
nb_bytes_read = p.StandardOutput.Read(buffer, 0, buffer.Length);
sb_stdout.Append(new string(buffer, 0, nb_bytes_read));
} while (nb_bytes_read > 0);
if (sb_stdout.ToString().EndsWith("\n(fcsh) "))
break;
Thread.Sleep(20);
}
基于我(可能是坏的)假设Process.StandardOutput在使用时被破坏:
我决定直接尝试使用Windows的API。我用这样的代码添加了答案;它工作正常(至少现在)。
我使用现在使用的代码创建了blog entry。
答案 0 :(得分:4)
我上周刚刚与...进行了斗争和斗争...出于某种原因,除了Read()调用之外的任何事情(ReadToEnd()都不是我需要的)似乎阻止并且永远不会返回。这就是我最终做到的“工作”:
剪辑1:
private bool ThreadExited = true;
private bool ExitThread = false;
private void ReadThread()
{
while (!ExitThread)
{
string Output = "";
int CharacterInt = myProcess.StandardOutput.Read();
while (CharacterInt > 0)
{
char Character = (char)CharacterInt;
Output += Character;
var MyDelegate = new delegateUpdateText(UpdateText);
Invoke(MyDelegate, Output);
Output = "";
CharacterInt = myProcess.StandardOutput.Read();
}
System.Threading.Thread.Yield();
}
ThreadExited = true;
}
剪辑2:
private void InitializeProcess()
{
ThreadExited = true;
ExitThread = true;
while (!ThreadExited)
System.Threading.Thread.Sleep(1000);
ThreadExited = false;
ExitThread = false;
myProcess = new Process();
ProcessStartInfo PSI = myProcess.StartInfo;
PSI.FileName = @"cmd.exe";
PSI.UseShellExecute = false;
PSI.RedirectStandardError = false;
PSI.RedirectStandardInput = true;
PSI.RedirectStandardOutput = true;
PSI.CreateNoWindow = false;
PSI.ErrorDialog = true;
myProcess.StartInfo = PSI;
myProcess.Exited += new EventHandler(myProcess_Exited);
myProcess.EnableRaisingEvents = false;
myProcess.Start();
ReadThreadThread = new System.Threading.Thread(ReadThread);
ReadThreadThread.Start();
}
private System.Threading.Thread ReadThreadThread;
终于最终为我工作了。在我的情况下,我正在写文本到文本框,但这应该很容易修改为其他东西。但是我做的其他事情都因块而引起了问题;由于某种原因,即使我使用反射来获取可用的字节数,调用ReadBlock()函数也会阻塞。从来没有让我满意。
答案 1 :(得分:2)
在与Ben Voigt讨论这个问题之后,我决定在不使用System.Diagnostics.Process的情况下实现与流程的通信。这就是我现在想出来的,它很有效,即它每次都能保持一致,没有任何阻塞或挂起。
我发布这个,因为这可能有助于任何人需要从stdout / stderr读取并在没有System.Diagnostics.Process的情况下写入某个已创建进程的stdin。
const UInt32 STARTF_USESTDHANDLES = 0x00000100;
const int HANDLE_FLAG_INHERIT = 1;
struct PROCESS_INFORMATION
{
public IntPtr hProcess;
public IntPtr hThread;
public uint dwProcessId;
public uint dwThreadId;
}
struct STARTUPINFO
{
public uint cb;
public string lpReserved;
public string lpDesktop;
public string lpTitle;
public uint dwX;
public uint dwY;
public uint dwXSize;
public uint dwYSize;
public uint dwXCountChars;
public uint dwYCountChars;
public uint dwFillAttribute;
public uint dwFlags;
public short wShowWindow;
public short cbReserved2;
public IntPtr lpReserved2;
public IntPtr hStdInput;
public IntPtr hStdOutput;
public IntPtr hStdError;
}
struct SECURITY_ATTRIBUTES
{
public int length;
public IntPtr lpSecurityDescriptor;
[MarshalAs(UnmanagedType.Bool)]
public bool bInheritHandle;
}
[DllImport("kernel32.dll")]
static extern bool CreateProcess(string lpApplicationName,
string lpCommandLine,
IntPtr lpProcessAttributes,
IntPtr lpThreadAttributes,
bool bInheritHandles,
uint dwCreationFlags,
IntPtr lpEnvironment,
string lpCurrentDirectory,
ref STARTUPINFO lpStartupInfo,
out PROCESS_INFORMATION lpProcessInformation);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CloseHandle(IntPtr hObject);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool CreatePipe(out IntPtr hReadPipe,
out IntPtr hWritePipe,
ref SECURITY_ATTRIBUTES lpPipeAttributes,
uint nSize);
[DllImport("kernel32", SetLastError = true)]
static extern unsafe bool ReadFile(IntPtr hFile,
void* pBuffer,
int NumberOfBytesToRead,
int* pNumberOfBytesRead,
IntPtr lpOverlapped);
[DllImport("kernel32.dll")]
static extern unsafe bool WriteFile(IntPtr hFile,
void* pBuffer,
int nNumberOfBytesToWrite,
int* lpNumberOfBytesWritten,
IntPtr lpOverlapped);
[DllImport("kernel32.dll")]
static extern bool SetHandleInformation(IntPtr hObject, int dwMask, uint dwFlags);
void OpenAndCloseFcsh()
{
STARTUPINFO si = new STARTUPINFO();
SECURITY_ATTRIBUTES sa = new SECURITY_ATTRIBUTES();
PROCESS_INFORMATION pi = new PROCESS_INFORMATION();
sa.bInheritHandle = true;
sa.lpSecurityDescriptor = IntPtr.Zero;
sa.length = Marshal.SizeOf(typeof(SECURITY_ATTRIBUTES));
sa.lpSecurityDescriptor = IntPtr.Zero;
IntPtr h_stdout_r, h_stdout_w;
if (!CreatePipe(out h_stdout_r, out h_stdout_w, ref sa, 0))
throw new Exception("bad");
if (!SetHandleInformation(h_stdout_r, HANDLE_FLAG_INHERIT, 0))
throw new Exception("bad");
IntPtr h_stdin_r, h_stdin_w;
if (!CreatePipe(out h_stdin_r, out h_stdin_w, ref sa, 0))
throw new Exception("bad");
if (!SetHandleInformation(h_stdin_w, HANDLE_FLAG_INHERIT, 0))
throw new Exception("bad");
si.wShowWindow = 0;
si.cb = (uint)Marshal.SizeOf(si);
si.dwFlags |= STARTF_USESTDHANDLES;
si.hStdOutput = h_stdout_w;
si.hStdError = h_stdout_w;
si.hStdInput = h_stdin_r;
string command = @"C:\flex_sdks\flex_sdk_4.5.1.21328_trimmed\bin\fcsh.exe";
if (!CreateProcess(command, null, IntPtr.Zero, IntPtr.Zero, true, 0, IntPtr.Zero, null, ref si, out pi))
throw new Exception("bad");
Console.WriteLine("Process ID (PID): " + pi.dwProcessId);
Console.WriteLine("Process Handle : " + pi.hProcess);
// ****************************************************
// let's interact with our process
// first read to the prompt
Console.WriteLine("read this from fcsh.exe:\r\n" + ReadTillPrompt(h_stdout_r));
// write "help" to stdin
byte[] bytes_to_write = Encoding.UTF8.GetBytes("help\r\n");
Write(h_stdin_w, bytes_to_write, 0, bytes_to_write.Length);
// then read to the prompt again
Console.WriteLine("read this from fcsh.exe:\r\n" + ReadTillPrompt(h_stdout_r));
// write "quit" to stdin
bytes_to_write = Encoding.UTF8.GetBytes("quit\r\n");
Write(h_stdin_w, bytes_to_write, 0, bytes_to_write.Length);
// ****************************************************
if (!CloseHandle(pi.hProcess))
throw new Exception("bad");
if (!CloseHandle(pi.hThread))
throw new Exception("bad");
if (!CloseHandle(h_stdout_w))
throw new Exception("bad");
if (!CloseHandle(h_stdin_w))
throw new Exception("bad");
}
public string ReadTillPrompt(IntPtr h_stdout_r)
{
StringBuilder sb = new StringBuilder(1024);
byte[] buffer = new byte[128];
int nb_bytes_read;
while (true) {
nb_bytes_read = Read(h_stdout_r, buffer, 0, buffer.Length);
sb.Append(Encoding.UTF8.GetString(buffer, 0, nb_bytes_read));
if (sb.ToString().EndsWith("\n(fcsh) "))
break;
Thread.Sleep(20);
}
return sb.ToString();
}
public unsafe int Read(IntPtr h, byte[] buffer, int index, int count)
{
int n = 0;
fixed (byte* p = buffer) {
if (!ReadFile(h, p + index, count, &n, IntPtr.Zero))
throw new Exception("bad");
}
return n;
}
public unsafe int Write(IntPtr h, byte[] buffer, int index, int count)
{
int n = 0;
fixed (byte* p = buffer) {
if (!WriteFile(h, p + index, count, &n, IntPtr.Zero))
throw new Exception("bad");
}
return n;
}
答案 2 :(得分:1)
从你的帖子中你不清楚你的意思是“我需要在进程写入后立即同步读取它。”如果您需要立即反馈,则需要异步管理。
<强>伪代码:强>
同步管理:
string sOutput = process.StandardOutput.ReadToEnd();
process.WaitToExit();
异步管理:
/*subscribe to events in order to receive notification*/
p.StartInfo.RedirectStandardInput = true;
p.OutputDataReceived += Subscription
之后如果你需要p.WaitForExit();
,如果你不在乎它什么时候完成但只是想要它的数据,你甚至可以避免这一行。
希望这有帮助。
答案 3 :(得分:1)