【发布时间】:2012-07-05 13:17:36
【问题描述】:
我的目标是在我的程序中执行一个外部可执行文件。首先,我使用了system() 函数,但我不想让用户看到控制台。所以,我搜索了一下,发现CreateProcess()函数。但是,当我尝试将参数传递给它时,我不知道为什么,它失败了。我从 MSDN 拿了这段代码,做了一点改动:
#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要求其第二个参数(如果提供)是非常量字符串。我不确定这在实践中是否存在问题,但为了完整起见,我想提一下。 -
...否则,AV 发生在哪里?你有调用栈吗?
-
@reuben Uhm...我不太确定,但我猜这是调用堆栈的输出:
kernel32.dll!76da70ac() [Frames below may be incorrect and/or missing, no symbols loaded for kernel32.dll] > msvcr100d.dll!_nh_malloc_dbg(unsigned int nSize, int nhFlag, int nBlockUse, const char * szFileName, int nLine) Line 302 + 0x1d bytes C++
标签: c winapi createprocess