system() and CreateProcess() / CreateProcessW()
我想在C程序中执行TEST.exe。当我使用
1 | system("TEST.exe <input-file> output-file" ); |
我能达到我的期望。
但是当我使用以下代码时,CreateProcessW()无法正常工作(请参阅如何运行外部程序?):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | if (CreateProcessW(const_cast<LPCWSTR>(FullPathToExe.c_str()), pwszParam, 0, 0, false, CREATE_DEFAULT_ERROR_MODE, 0, 0, &siStartupInfo, &piProcessInfo) != false) { /* Watch the process. */ dwExitCode = WaitForSingleObject(piProcessInfo.hProcess, (SecondsToWait * 1000)); iReturnVal = GetLastError(); } else { /* CreateProcess failed */ iReturnVal = GetLastError(); } |
其中
1 | FullPathToExe="TEST.exe", pwszParam="TEST.exe <input-file> output-file". |
WaitForSingleObject()返回258,GetLastError()返回1813("在图像文件中找不到指定的资源类型。")。
此外,当我使用
运行我自己的HelloProcess.exe(打印问候,并hibernate由以下数字确定的几秒钟,然后退出)时,上面的CreateProcessW()代码可以正常工作。
1 | FullPathToExe="HelloProcess.exe", pwszParam="HelloProcess.exe 10". |
有什么想法吗?感谢您的提示!
The system function passes command to the command interpreter, which executes the string as an operating-system command. system refers to the COMSPEC and PATH environment variables that locate the command-interpreter file (the file named CMD.EXE in Windows NT). If command is NULL, the function simply checks to see whether the command interpreter exists.
—Documentation ofsystem
这就是为什么诸如
我做什么CreateProcess和命令行参数
告诉我去做,并解决问题!谢谢大家的关注!
为方便起见,这是答案的引号:
You cannot use command-line redirection operators with CreateProcess()
directly. You have to spawn an instance of cmd.exe and pass the
operators to it instead, eg:
1 CreateProcess("C:\\\\windows\\\\system32\\\\cmd.exe", t_str2, ...))Where
t_str2 is"/C C:\\Temp\\sift.exe < C:\\img1.pgm > C:\\img1.key". The
actual path to cmd.exe can be determined by reading the %COMSPEC%
environment variable.
WaitForSingleObject()返回等待结果,而不是退出代码。 https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms687032(v = vs.85).aspx
258是WAIT_TIMEOUT。您应该重试此错误代码,直到获得返回值0(WAIT_OBJECT_0)或其他错误。
在此之后,请使用GetExitCodeProcess https://msdn.microsoft.com/zh-cn/library/windows/desktop/ms683189(v=vs.85).aspx
获取进程的退出代码。