我从一个asp.net核心应用程序运行一个进程:
bool createShell = true;
//generate output pdf
using var pdfGeneratorProcess = new System.Diagnostics.Process
{
StartInfo = new ProcessStartInfo
{
UseShellExecute = createShell,
CreateNoWindow = createShell,
RedirectStandardError = !createShell,
RedirectStandardOutput = !createShell,
WorkingDirectory = dir,
FileName = "java",
Arguments = $"-cp \"fop-2.0.jar;lib/*\"; FOPLocalPDFGenerator {rendererFile} {inputFile} {outputFile}"
}
};
_logger.LogInformation("{CMD}", $"{pdfGeneratorProcess.StartInfo.FileName} {pdfGeneratorProcess.StartInfo.Arguments}");
pdfGeneratorProcess.Start();
当createShell为真时,进程会写入一些PDF文件并退出。当我将其设置为false时,它运行的StandardOutput和StandardError似乎是相同的,但从未完成,而且PDF文件是空的。
当没有可见控制台窗口时,进程为什么挂起?
发布于 2021-02-05 08:40:45
当ProcessStartInfo.RedirectStandardOutput为真时,进程的输出将重定向到Process.StandardOutput。
但是在OP代码中,Process.StandardOutput
不被读取,缓冲区被填充到极限。当达到极限时,进程就不能编写Process.StandardOutput
并等待一些空闲空间。
ProcessStartInfo.RedirectStandardError和Process.StandardError也有同样的故事
一种解决方案是将ProcessStartInfo.RedirectStandardOutput
和ProcessStartInfo.RedirectStandardError
设置为false。
如果需要输出,则可以将输出重定向到其他流。请参见将输出重定向到文件的示例:
void Redirect(StreamReader output, StreamWriter to)
{
string textLine;
while ((textLine = output.ReadLine()) != null)
{
to.WriteLine(textLine);
}
}
bool createShell = true;
//generate output pdf
using var pdfGeneratorProcess = new System.Diagnostics.Process {
StartInfo = new ProcessStartInfo {
UseShellExecute = createShell,
CreateNoWindow = !createShell, // I inversed the condition
RedirectStandardError = !createShell,
RedirectStandardOutput = !createShell,
WorkingDirectory = dir,
FileName = "java",
Arguments = $"-cp \"fop-2.0.jar;lib/*\"; FOPLocalPDFGenerator {rendererFile} {inputFile} {outputFile}"
}
};
_logger.LogInformation("{CMD}", $"{pdfGeneratorProcess.StartInfo.FileName} {pdfGeneratorProcess.StartInfo.Arguments}");
pdfGeneratorProcess.Start();
using (StreamWriter writer = File.CreateText(@"C:\Temp\log.txt"))
{
var standardOutputThread = new Thread(new ThreadStart(() => Redirect(pdfGeneratorProcess.StandardOutput, writer)));
var errorOutputThread = new Thread(new ThreadStart(() => Redirect(pdfGeneratorProcess.StandardError, writer)));
standardOutputThread.Start();
errorOutputThread.Start();
standardOutputThread.Join();
errorOutputThread.Join();
}
pdfGeneratorProcess.WaitForExit();
https://stackoverflow.com/questions/66059598
复制相似问题