我的目標是在我的程序中執行外部可執行文件。首先,我使用了system()
函數,但我不希望用戶看到控制檯。於是,我搜索了一下,發現了CreateProcess()
的功能。但是,當我嘗試將參數傳遞給它時,我不知道爲什麼,它失敗了。我從MSDN拿了這段代碼,並且改了一點:CreateProcess()失敗並出現訪問衝突
#include <windows.h>
#include <stdio.h>
#include <tchar.h>
void _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;
}
*/
// Start the child process.
if(!CreateProcess(NULL, // No module name (use command line)
L"c:\\users\\e\\desktop\\mspaint.exe", // 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;
}
// Wait until child process exits.
WaitForSingleObject(pi.hProcess, INFINITE);
// Close process and thread handles.
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
但是,這個代碼以某種方式創建了訪問衝突。我可以在不顯示用戶控制檯的情況下執行mspaint嗎?
非常感謝。
一方面,'CreateProcess'要求(如果有的話)的第二個參數是一個非常量字符串。我不確定這在實踐中是否存在問題,但我想完整地提及它。 – reuben
...否則,AV在哪裏發生?你有一個調用堆棧嗎? – reuben
@reuben呃...我不太確定,但我想這是調用堆棧的輸出:'kernel32.dll!76da70ac()\t \t [下面的幀可能不正確和/或丟失,沒有加載符號爲KERNEL32.DLL] \t > \t msvcr100d.dll!_nh_malloc_dbg(無符號整數n大小,INT nhFlag,INT nBlockUse,常量字符* szFileName,INT n線段)線302 + 0x1d字節\t C++' –