2014-12-05 210 views
-1

Hellp。在我的'管道'中,我有3个应该按顺序执行的命令,并且每个请求都必须等到上一个命令结束。现在我已经完成了第一个请求,但第二个和第三个只是跳过... 你能否建议如何改变这个'管道'?在cmd中执行几个命令。执行只有一个命令

string strCmdText = s1; 
var startInfo = new ProcessStartInfo 
    { 
    FileName = "cmd.exe", 
    RedirectStandardInput = true, 
    RedirectStandardOutput = true, 
    UseShellExecute = false, 
    CreateNoWindow = true 
    }; 

var process = new Process { StartInfo = startInfo }; 
process.Start(); 
process.StandardInput.WriteLine(strCmdText); 
process.WaitForExit(); 

string strCmdText1 = s2; 
process.StandardInput.WriteLine(strCmdText1); 
process.WaitForExit(); 

string strCmdText2 = s3; 
process.StandardInput.WriteLine(strCmdText2); 
process.StandardInput.WriteLine("exit"); 

谢谢。

+1

首先,你为什么要通过CMD,第二,*究竟是什么*“不起作用”? – 2014-12-05 23:46:52

+1

刚刚检查了你的代码,一切都像魅力一样。 – 2014-12-05 23:56:37

+0

当我编写有意义的代码时,它工作正常。请注意,在您的示例中,在继续编写新命令之前,您需要调用WaitForExit()。当我尝试这样做时,我从未接触过下一个命令;它仍然停留在对'WaitForExit()'的调用中。如果您需要帮助,请提供一个很好的代码示例,并具体说明您正在尝试做什么,发生了什么,以及如何与您想要的不同。请参阅http://stackoverflow.com/help/mcve和http://stackoverflow.com/help/how-to-ask – 2014-12-06 00:07:33

回答

0

让我们通过代码:

  • 你开始的cmd.exe一个实例:

    var process = new Process { StartInfo = startInfo }; 
    process.Start(); 
    
  • 你写了一个命令,它的标准输入:

    process.StandardInput.WriteLine(strCmdText); 
    
  • 而且那么你等待cmd.exe退出:

    process.WaitForExit(); 
    
  • 现在,你写的另一个命令的标准输入:

    string strCmdText1 = s2; 
    process.StandardInput.WriteLine(strCmdText1); 
    
  • 等待,什么?cmd.exe在上一步中退出,所以没有更多的过程可以发送命令。

  • 然后你等待进程退出,但它已经死了很久以前的事:

    process.WaitForExit(); 
    
  • 你重复相同的非工作代码:

    string strCmdText2 = s3; 
    process.StandardInput.WriteLine(strCmdText2); 
    process.StandardInput.WriteLine("exit"); 
    

你应该更好地理解现在的问题。看起来好像cmd.exe在执行第一个命令后退出。

有几件事情,你可以尝试:

  • 获得完全摆脱cmd.exe。除非执行一些批处理脚本,否则可以直接调用预期的可执行文件(如python.exe)。

  • 为您的3个命令启动3个不同的cmd.exe实例。

  • 尝试将一些参数传递给cmd.exe,如/Q

先尝试第一种方法,它是最干净的方法。