C++ 的 windows.h 头文件中引入的 CreatProcess 函数存在严重问题。 每当我尝试向它传递一个包含 cmd 命令的 TCHAR 变量时,它都会返回错误:CreateProcess failed (2)。 为此,我正在等待您的解释和解决方案。
考虑下面的代码:
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
int _tmain( int argc, TCHAR *argv[] )
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory( &si, sizeof(si) );
si.cb = sizeof(si);
ZeroMemory( &pi, sizeof(pi) );
if( argc != 2 )
{
printf("Usage: %s [cmdline]\n", argv[0]);
return 0;
}
// Start the child process.
if( !CreateProcess( NULL, // No module name (use command line)
argv[1], // Command line
NULL, // Process handle not inheritable
NULL, // Thread handle not inheritable
FALSE, // Set handle inheritance to FALSE
0, // No creation flags
NULL, // Use parent's environment block
NULL, // Use parent's starting directory
&si, // Pointer to STARTUPINFO structure
&pi ) // Pointer to PROCESS_INFORMATION structure
)
{
printf( "CreateProcess failed (%d).\n", GetLastError() );
return 0;
}
// Wait until child process exits.
WaitForSingleObject( pi.hProcess, INFINITE );
// Close process and thread handles.
CloseHandle( pi.hProcess );
CloseHandle( pi.hThread );
注意:当我启动一个指定路径的应用程序时..它工作正常就像=> "c:\code.exe";
最佳答案
如果你想运行命令DOS
, 你必须运行 shell cmd
之前。
CreateProcess
不会为你那样做。
选项/c
的 cmd
允许在 shell 中运行命令并终止。您只需要构建一个 cmd /c <your command here>
类型的命令行.
我在 VS2012 上编译了你的代码,我试过了:test.exe "cmd /c dir"
它就像一个魅力。
来自微软文档:
To run a batch file (or a batch command), you must start the command interpreter; set lpApplicationName to cmd.exe and set lpCommandLine to the following arguments: /c plus the name of the batch file.
来源:http://msdn.microsoft.com/en-us/library/windows/desktop/ms682425(v=vs.85).aspx
关于c++ - 为什么不使用 CreateProcess 执行命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17778351/