我有Delphi代码,该代码用于通过给定的参数集从JAVA_HOME运行Java.exe。这是通过将命令行命令传递给CreateProcess()来实现的。对于一组特定的输入参数,这给我一个错误,提示“无法创建Java虚拟机”。我需要通过PeekNamedPipe()将其获取到Delphi代码中,并将其显示在应用程序中。我该如何实现?Delphi代码如下所示:
begin
securityAttr.nlength := SizeOf(TSecurityAttributes);
securityAttr.binherithandle := true;
securityAttr.lpsecuritydescriptor := nil;
if CreatePipe (readPipe, writePipe, @securityAttr, 0) then
begin
buffer := AllocMem(READ_BUFFER + 1);
FillChar(startInfo, Sizeof(startInfo), #0);
startInfo.cb := SizeOf(startInfo);
startInfo.hStdOutput := writePipe;
startInfo.hStdInput := readPipe;
startInfo.dwFlags := STARTF_USESTDHANDLES + STARTF_USESHOWWINDOW;
startInfo.wShowWindow := SW_HIDE;
if SearchPath(nil, PChar(consoleApp), '.exe', SizeOf(consoleAppBuf), consoleAppBuf, exeName) = 0 then
raise EInOutError.CreateFmt('Could not find file %s', [consoleApp]);
FmtStr(commandLine, '"%s" %s', [consoleAppBuf, parameters]);
if CreateProcess(nil, PChar(commandLine), nil, nil, true, CREATE_NO_WINDOW, nil, nil, startInfo, processInfo) then
begin
totalBytesRead := 0;
repeat
exitCode := WaitForSingleObject(ProcessInfo.hProcess, 100);
Application.ProcessMessages;
if (PeekNamedPipe(readPipe, @buffer[totalBytesRead],
READ_BUFFER, @bytesRead,
@totalBytesAvail, @bytesLeftThisMessage)) then
begin
if (bytesRead > 0) then
ReadFile(readPipe, buffer[totalBytesRead], bytesRead, bytesRead, nil);
totalBytesRead := totalBytesRead + bytesRead;
end;
until (exitCode <> WAIT_TIMEOUT);
GetExitCodeProcess(ProcessInfo.hProcess, result);
buffer[totalBytesRead]:= #0;
OemToChar(buffer, buffer);
output.Text := output.Text + StrPas(buffer);
FreeMem(buffer);
CloseHandle(processInfo.hProcess);
CloseHandle(processInfo.hThread);
CloseHandle(readPipe);
CloseHandle(writePipe);
end
else
RaiseLastWin32Error;
end;
如何读取java.exe引发的错误?
将同一管道的两端连接到同一过程的输入和输出是错误的。您正在将流程的输出反馈回其输入。保留hStdInput
为NULL
。
您还会通过错误检查快速而轻松地玩游戏,并且由于不使用finally
积木,因此存在句柄泄漏的风险。而且我也不喜欢忙碌的循环。或致电ProcessMessages
。
撇开所有这些,您不阅读错误的可能原因是它们进入了stderr。将管道的写入端连接到stderr以及stdout:
startInfo.hStdOutput := writePipe;
startInfo.hStdError := writePipe;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句