c#运行守护进程命令行

标签 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);
}

最佳答案

要执行 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");
}   

关于c#运行守护进程命令行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23398774/

相关文章:

c# - 如何为一对 3D 向量实现 GetHashCode

c# - 为什么Regex.Replace留下括号?

windows - 了解 (set) 说明符的 CMD.EXE FOR 行为

windows - 7zip 递归归档文件夹中的文件

variables - 替换变量中的 "%"

windows - 命令 : '■m' is not recognized as an internal or external command

python - 从同一个批处理文件中读取第一行批处理文件?

c# - protobuf-net 到 .proto 生成枚举冲突?

c# - 匹配优于 C# 应用程序中的舍入

c# - 不能使用 lambda 表达式作为动态调度的参数