c++ - 为什么不使用 CreateProcess 执行命令

标签 c++ shell command

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不会为你那样做。

选项/ccmd允许在 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/

相关文章:

c++ - fopen 没有完全打开文件

C (UNIX),组合文件(字节数)

git - Android Studio 3.3.1中Github命令 "Update Project"和 "Pull"的区别?

c++ - 在执行 std::regex_replace 时去掉多余的空格

c++ - 如何在设计实现层面避免内存泄漏

c++ - 我怎样才能编辑这一行不再是一个警告

ruby-on-rails - Ruby 守护进程不会在系统启动时执行

linux - 在 shell 脚本的提示中检测并输入输入

shell - bash 中的 Grep 数字范围

c - 如何像 nm 命令一样显示符号的类型?