在window service中创建一个GUI进程,在service management中一旦start,会导致System.AccessViolationException
问题引入
1. 我创建了一个window service程序,然后在里面调用了CreateProcess(...)去创建一个进程;
2. 该创建的进程会创建一个system tray icon程序;
3. 当操作系统一旦启动,我希望我的window service就能被start,然后我的tray icon程序就能被启动;
实现细节
1. 在virtual void OnStart(array<String^>^ args) override中,我的实现如下:
virtual void OnStart(array<String^>^ args) override
{
// TODO: Add code here to start your service.
eventLog1->WriteEntry("In OnStart");
PROCESS_INFORMATION piProcInfo;
STARTUPINFO siStartInfo;
ZeroMemory(&siStartInfo, sizeof(siStartInfo));
// Set up members of STARTUPINFO structure.
siStartInfo.cb = sizeof(STARTUPINFO);
siStartInfo.lpReserved = NULL;
siStartInfo.lpReserved2 = NULL;
siStartInfo.cbReserved2 = 0;
siStartInfo.lpDesktop = NULL;
siStartInfo.dwFlags = 0;
BOOL bFlag = CreateProcess(NULL, _T("D:\\MAPGuiEngine.exe"), NULL, NULL,FALSE, 0, NULL, NULL, &siStartInfo, &piProcInfo);
DWORD dwError = ::GetLastError();
// Wait for the processs to finish
DWORD rc = WaitForSingleObject(
piProcInfo.hProcess, // process handle
INFINITE);
}
这个里面只简单的做了一个创建进程的操作,并且,我是在另外一个Dialog based的程序中调试过这个函数,是能够成功创建MAPGuiEngine.exe的。
问题log
由于window service无法跟踪,我用eventlog 去观察了错误的产生,是由于
Service cannot be started. System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at CreateProcessW(Char* , Char* , _SECURITY_ATTRIBUTES* , _SECURITY_ATTRIBUTES* , Int32 , UInt32 , Void* , Char* , _STARTUPINFOW* , _PROCESS_INFORMATION* )
at MotorolaMobileDeviceService.MotorolaMobileDeviceServiceWinService.OnStart(String[] args)
at System.ServiceProcess.ServiceBase.ServiceQueuedMainCallback(Object state)
另外,为了能够让service访问桌面程序, 按照下面步骤“MyService” -> Properties -> Log on -> Local System Account -> “Allow service to interace with Desktop”, however, it looks the issue still exists.
肯请专家不吝赐教解决方案,非常感谢。