c#running daemon命令行

时间:2014-04-30 22:01:21

标签: c# batch-file

我有几个需要使用C#执行的批处理文件,问题是在第一个批处理文件的末尾运行一个守护进程。由于WaitForExit(),这导致永远不会执行第二个批处理文件。我不能解决这个问题,因为我不知道第一批文件需要运行多长时间(直到它运行守护进程)

BatchFile1.bat ->
BatchFile2.bat ->
BatchFile3.bat ->
BatchFile4.bat
在BatchFile1.bat里面,我有哇哇,哇哇,等等,最后它正在运行一个守护进程,当然永远不会退出

//not exit , even if there is error
public void Run_Process(string process_name, string s)     
{                
    Process myProcess = new Process();

    myProcess.StartInfo.UseShellExecute = false;
    myProcess.StartInfo.FileName = "cmd.exe";
    myProcess.StartInfo.Arguments = "/C " + process_name + s;

    myProcess.StartInfo.CreateNoWindow = true;
    myProcess.StartInfo.RedirectStandardOutput = true;
    myProcess.StartInfo.RedirectStandardError = true;
    myProcess.Start();
    string standard_output = myProcess.StandardOutput.ReadToEnd();
    myProcess.WaitForExit();
    Console.WriteLine(standard_output);
}

1 个答案:

答案 0 :(得分:0)

要执行cmd.exe,这可能有效:

static void ExecuteCommand(string command)
{
int exitCode;
ProcessStartInfo processInfo;
Process process;

processInfo = new ProcessStartInfo("cmd.exe", "/c " + command);
processInfo.CreateNoWindow = true;
processInfo.UseShellExecute = false;
// *** Redirect the output ***
processInfo.RedirectStandardError = true;
processInfo.RedirectStandardOutput = true;

process = Process.Start(processInfo);
process.WaitForExit();

// *** Read the streams ***
string output = process.StandardOutput.ReadToEnd();
string error = process.StandardError.ReadToEnd();

exitCode = process.ExitCode;

Console.WriteLine("output>>" + (String.IsNullOrEmpty(output) ? "(none)" : output));
Console.WriteLine("error>>" + (String.IsNullOrEmpty(error) ? "(none)" : error));
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
}

static void Main()
{
ExecuteCommand("echo testing");
}