【发布时间】:2015-03-05 11:23:48
【问题描述】:
我正在使用辅助类来运行外部进程:
class ExternalProcessRunner
{
static public string Run(string program, string parameters)
{
output = "";
error = "";
try
{
ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = true;
startInfo.UseShellExecute = false;
startInfo.FileName = program;
startInfo.Arguments = parameters;
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.WindowStyle = ProcessWindowStyle.Minimized;
startInfo.RedirectStandardError = true;
startInfo.RedirectStandardOutput = true;
StringBuilder outputSB = new StringBuilder();
StringBuilder errorSB = new StringBuilder();
using (Process exeProcess = Process.Start(startInfo))
using (AutoResetEvent outputWaitHandle = new AutoResetEvent(false))
using (AutoResetEvent errorWaitHandle = new AutoResetEvent(false))
{
exeProcess.OutputDataReceived += (sender, e) =>
{
if (e.Data == null)
{
outputWaitHandle.Set();
}
else
{
outputSB.AppendLine(e.Data);
}
};
exeProcess.ErrorDataReceived += (sender, e) =>
{
if (e.Data == null)
{
errorWaitHandle.Set();
}
else
{
errorSB.AppendLine(e.Data);
}
};
exeProcess.Start();
exeProcess.BeginOutputReadLine();
exeProcess.BeginErrorReadLine();
exeProcess.WaitForExit();
outputWaitHandle.WaitOne();
errorWaitHandle.WaitOne();
output = outputSB.ToString();
error = errorSB.ToString();
}
}
catch (Exception e)
{
return e.Message;
}
return "";
}
static public string output;
static public string error;
}
它用于运行 perl 脚本,该脚本接受文件名,打开文件,写入一些信息并关闭文件。然后 C# 代码打开该文件进行读取。有时我会遇到异常: “该进程无法访问文件'tmp_file.txt',因为它正被另一个进程使用。” 什么会导致问题?如何解决?我认为我正在确保进程结束,这意味着释放所有句柄。
【问题讨论】:
-
可能是脚本没有正确退出(有时),所以文件从那里打开..
-
了解打开文件的进程将是很好的第一步。在 Windows SysInternal 的 Process Explorer 和 Handles 工具上将为您提供这些信息。