简体   繁体   English

控制台vs Windows窗体上的Process.WaitForExit()

[英]Process.WaitForExit() on Console vs Windows Forms

I have a console app and a win forms app that both need to call out to a remote server for some data, they make a call to the command line part of Putty, plink.exe, to run a remote command over SSH. 我有一个控制台应用程序和一个Win Forms应用程序,它们都需要向远程服务器调出一些数据,它们调用Putty的命令行部分plink.exe,以通过SSH运行远程命令。

I created a tiny class library for both to share, running the following: 我创建了一个微型类库供两者共享,并运行以下命令:

public static string RunCommand(string command, string arguments) {
  ProcessStartInfo startInfo = new ProcessStartInfo {
      FileName = command,
      Arguments = arguments,
      UseShellExecute = false,
      CreateNoWindow = true,
      RedirectStandardOutput = true
  };
  string output = null;
  using (Process p = new Process()) {
      p.StartInfo = processStartInfo;
      p.Start();
      output = p.StandardOutput.ReadToEnd();
      p.WaitForExit();
  }
  return output;
}

Under the console application everything works fine, under the win forms it doesn't error, it seems that WaitForExit() just doesn't wait. 在控制台应用程序下,一切正常,在胜利形式下,它没有错误,似乎WaitForExit()只是不等待。 I get an empty string for output. 我得到一个空字符串用于输出。 I've confirmed from the remote server the user logged in, so it seems the command has run. 我已从远程服务器确认用户已登录,因此似乎命令已运行。

Any ideas? 有任何想法吗?

Under Windows Console applications have STDIN, STDOUT, and STDERR. 在Windows控制台下,应用程序包括STDIN,STDOUT和STDERR。 Windowed applications do not. 窗口应用程序则没有。 When you create a process under a Console application the STDIN etc. are inherited by the child application. 在控制台应用程序下创建进程时,子应用程序将继承STDIN等。 This does not happen in the Windowed application. 在窗口应用程序中不会发生这种情况。

The RedirectStandardInput=true works because it makes the system create a Writer for the STDIN that you can use to send input to the child process. RedirectStandardInput=true起作用是因为它使系统为STDIN创建Writer,您可以使用该Writer将输入发送到子进程。 In your case the child doesn't need the input it just needs the presence of the input. 在您的情况下,孩子不需要输入,只需要输入的存在即可。 YMMV. 因人而异。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM