未指定路径时,CreateProcess与ShellExecute(Ex) 查找路径之不同
几天前碰上的一个比较细节的东西。调用CreateProcess时不指定全路径时(如:devenv.exe)就不成功(返回0),而同样是不带路径,开始-》运行(与ShellExecute 相当?我想)则完全OK,可以正常开户vs的开发环境。最后原因是——没有把devenv.exe所在的路径加入环境变量PATH里。这倒打破了我一直以来的一个错误认识,即开始-》运行OK的话就说明环境变量设定也是OK的。
查查CreateProcess相关的MSDN。
http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
If the file name does not contain a directory path, the system searches for the executable file in the following sequence:
- 1. The
directory from which the application loaded. - 2. The
current directory for the parent process. - 3. The
32-bit Windows system directory. Use the GetSystemDirectory function
to get the path of this directory. - 4. The
16-bit Windows system directory. There is no function that obtains the path of this directory, but it is searched. The name of this directory is System. - 5. The
Windows directory. Use the GetWindowsDirectory function
to get the path of this directory. - 6. The
directories that are listed in the PATH environment variable.Note that this function does not search the per-application path specified by the App
Paths registry key. To include this per-application path in the search sequence, use theShellExecute function.
http://msdn.microsoft.com/en-us/library/windows/desktop/ee872121(v=vs.85).aspx
Finding an Application Executable
When the ShellExecuteEx function
is called with the name of an executable file in its lpFile parameter,
there are several places where the function looks for the file. We recommend registering your application in the App Paths registry
subkey. Doing so avoids the need for applications to modify the system PATH environment variable.
The file is sought in the following locations:
- The current working directory.
- The Windows directory
only (no subdirectories are searched). - The Windows\System32 directory.
- Directories listed in the PATH environment variable.
- Recommended: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\App
Paths
到此,一切真相大白。只差注册表中App Paths注册项里的内容,即CreateProcess不查找这个注册表项目,而ShellExecute(Ex) 查找。
参考资料(特别感谢zhangyan87815的回答):