Process.WaitForExit()在控制台上与Windows窗体 [英] Process.WaitForExit() on Console vs Windows Forms

查看:588
本文介绍了Process.WaitForExit()在控制台上与Windows窗体的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个控制台应用程序和一个win表单应用程序,都需要调用到远程服务器的一些数据,他们调用命令行部分Putty,plink.exe,通过SSH运行远程命令。

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.

我创建了一个小型类库,可以共享,运行以下内容:

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;
}

在控制台应用程序下,一切正常,错误,似乎WaitForExit()只是不等待。我得到一个空字符串输出。

Under the console application everything works fine, under the win forms it doesn't error, it seems that WaitForExit() just doesn't wait. 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.

任何想法?

推荐答案

在Windows控制台应用程序下有STDIN,STDOUT和STDERR。窗口应用程序不。当在控制台应用程序下创建进程时,STDIN等由子应用程序继承。

Under Windows Console applications have STDIN, STDOUT, and STDERR. Windowed applications do not. When you create a process under a Console application the STDIN etc. are inherited by the child application. This does not happen in the Windowed application.

RedirectStandardInput = true 的工作原理是使系统创建一个Writer用于可以用于将输入发送到子进程的STDIN。在你的情况下,孩子不需要输入,只需要输入的存在。 YMMV。

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. In your case the child doesn't need the input it just needs the presence of the input. YMMV.

这篇关于Process.WaitForExit()在控制台上与Windows窗体的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆