2013-07-22 44 views
1

我在使用C++的windows.h頭文件中引入了CreatProcess函數的hev問題。每當我嘗試傳遞一個包含cmd命令的TCHAR變量時,它會返回錯誤:CreateProcess failed(2)。 ,爲此我正在等待您的解釋和解決方案。爲什麼命令不能用CreateProcess執行

考慮下面的代碼:

#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」;

+0

在這種情況下,你的應用程序不工作?你在說:code.exe C:\ Code.exe正在工作? –

+0

以防將DOS命令作爲參數傳遞 – afr0ck

回答

0

爲了執行由命令shell實現的命令(又名cmd.exe),您需要實際運行cmd.exe。 CreateProcess不會自動爲你做。

構建cmd.exe /c <your command here>表單的命令行。 /c表示「運行一個命令,然後終止」。

1

如果要運行命令DOS,則必須先運行shell cmd

CreateProcess不適合你。

cmd的選項/c允許在shell中運行命令並終止。您只需構建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

相關問題