1

我在 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”;

4

2 回答 2

1

如果要运行命令DOS,则必须先运行 shell cmd

CreateProcess不适合你。

允许在 shell 中运行命令并终止/c的选项。cmd您只需要构建一个类型为cmd /c <your command here>.

我在 VS2012 上编译了你的代码并尝试了:test.exe "cmd /c dir"它就像一个魅力。

从微软文档:

要运行批处理文件(或批处理命令),您必须启动命令解释器;将 lpApplicationName 设置为 cmd.exe 并将 lpCommandLine 设置为以下参数:/c 加上批处理文件的名称。

来源: http: //msdn.microsoft.com/en-us/library/windows/desktop/ms682425 (v=vs.85).aspx

于 2013-07-22T06:37:08.563 回答
0

为了执行由命令 shell aka 实现的命令cmd.exe,您需要实际运行 cmd.exe。CreateProcess不会自动为您执行此操作。

建立一个形式的命令行cmd.exe /c <your command here>/c意思是“运行一个命令,然后终止”。

于 2013-07-22T04:20:17.213 回答