如何使用 process 到 运行 几个命令

How to use process to run several commands

我有一个进程,用它来运行几个命令。

Process mycmd = new Process();

    mycmd.StartInfo = startInfo1;
    mycmd.Start();
    if (mycmd.ExitCode > 0)
    {
    // do something
    }
    mycmd.StartInfo = startInfo2;
    mycmd.Start();
    if (mycmd.ExitCode > 0)
    {
    // do something else
    }

第一次执行命令时,退出代码为 1。第二次 运行 也会保存它。如何重置退出代码? 另一个问题是 - 可以调用 "start" 两次吗?

每次在 Process 实例上调用 Start() 时,都会创建一个新进程,系统会为其分配资源。这些资源是进程句柄和其他属性,如退出代码和退出时间。如果你这样写:

var p = new Process();
p.StartInfo.FileName = "cmd.exe";
p.Start();
p.WaitForExit();
var exitCode = p.ExitCode;
Console.WriteLine("Handle: {0}, PID: {1}, Exit code: {2}", p.Handle.ToInt32(), p.Id, exitCode);

p.StartInfo.FileName = "cmd.exe";
p.Start();
p.WaitForExit();
exitCode = p.ExitCode;
Console.WriteLine("Handle: {0}, PID: {1}, Exit code: {2}", p.Handle.ToInt32(), p.Id, exitCode);

并使两个进程 return 具有不同的值(通过输入命令 windows 例如 exit 1exit 2),你会得到类似于这个的输出:

Handle: 1308, PID: 9060, Exit code: 1
Handle: 1324, PID: 8428, Exit code: 2

ExitCodeHandle 这样的进程属性正确地 return 最后终止进程的值。但是它们在之前的进程 运行 中丢失了,而且你还有一个 资源泄漏 因为为之前的进程分配的系统资源还没有被释放(以下引用来自 MSDN):

If a handle is open to the process, the operating system releases the process memory when the process has exited, but retains administrative information about the process, such as the handle, exit code, and exit time. To get this information, you can use the ExitCode and ExitTime properties. These properties are populated automatically for processes that were started by this component. The administrative information is released when all the Process components that are associated with the system process are destroyed and hold no more handles to the exited process.

Process 类型实现了 IDisposable 接口,当您在 Process 实例上调用 Close()(或 Dispose())时,这些组件被销毁(以下引用来自 MSDN):

The Close method causes the process to stop waiting for exit if it was waiting, closes the process handle, and clears process-specific properties. (...) The Dispose method calls Close. Placing the Process object in a using block disposes of resources without the need to call Close.

使用 Process 到 运行 两个进程的正确方法包括调用 Dispose():

using (var p = new Process())
{
    p.StartInfo.FileName = "cmd.exe";
    p.Start();
    p.WaitForExit();
    var exitCode = p.ExitCode;
    Console.WriteLine("Handle: {0}, PID: {1}, Exit code: {2}", p.Handle.ToInt32(), p.Id, exitCode);
}

using (var p = new Process())
{
    p.StartInfo.FileName = "cmd.exe";
    p.Start();
    p.WaitForExit();
    var exitCode = p.ExitCode;
    Console.WriteLine("Handle: {0}, PID: {1}, Exit code: {2}", p.Handle.ToInt32(), p.Id, exitCode);
}