CreateProcess()因访问冲突而失败

我的目标是在我的程序中执行外部可执行文件。 首先,我使用了system()函数,但我不希望向用户看到控制台。 所以,我搜索了一下,发现了CreateProcess()函数。 但是,当我尝试将参数传递给它时,我不知道为什么,它失败了。 我从MSDN中获取了这段代码,并稍作改动:

 #include  #include  #include  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吗?

非常感谢你。

试试这个,它应该工作。

 TCHAR lpszClientPath[500]= TEXT("c:\\users\\e\\desktop\\mspaint.exe"); if(!CreateProcess(NULL, lpszClientPath, NULL, NULL, FALSE, NORMAL_PRIORITY_CLASS|CREATE_NEW_CONSOLE|CREATE_UNICODE_ENVIRONMENT,NULL, NULL, &si, &pi)) { printf( "CreateProcess failed (%d).\n", GetLastError() ); return; } ... ... 

第二个参数是LPTSTR ,即指向非const char数组的指针。 文档具体说:

此参数不能是只读内存的指针(例如const变量或文字字符串)

传递字符串文字的原因是一个问题:

系统会在命令行字符串中添加一个终止空字符,以将文件名与参数分开。 这会将原始字符串分为两个字符串以进行内部处理。

这意味着在你的情况下,它试图修改只读内存,因此崩溃。

将您的代码更改为:

 #include  #include  #include  void _tmain( int argc, TCHAR *argv[] ) { TCHAR ProcessName[256]; STARTUPINFO si; PROCESS_INFORMATION pi; wcscpy(ProcessName,L"c:\\users\\e\\desktop\\mspaint.exe"); 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) ProcessName, // 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 ); }