2
我在寫一個Windows服務程序,它會在啓動時調用一個外部的exe文件,比如notepad.exe
。但它總是失敗,"unhandled win32 exception occured"
如何在服務程序中調用exe程序?
我的步驟:
- 代碼編譯成一個
exe
文件:MemoryStatus.exe
。 - 使用命令安裝服務:
sc create MemoryStatus binpath=c:\MyServices\MemoryStatus.exe
- 從Windows控制面板中找到該服務,然後單擊
Start
。 - 錯誤發生...
會有人幫助,表示我所做的是錯了嗎?
void main()
{
SERVICE_TABLE_ENTRY ServiceTable[2];
ServiceTable[0].lpServiceName = _T("MemoryStatus_new_3");
ServiceTable[0].lpServiceProc = (LPSERVICE_MAIN_FUNCTION)**ServiceMain**;
ServiceTable[1].lpServiceName = NULL;
ServiceTable[1].lpServiceProc = NULL;
StartServiceCtrlDispatcher(ServiceTable);
}
void ServiceMain(int argc, char** argv)
{
int error;
ServiceStatus.dwServiceType = SERVICE_WIN32;
ServiceStatus.dwCurrentState = SERVICE_START_PENDING;
ServiceStatus.dwControlsAccepted = SERVICE_ACCEPT_STOP | SERVICE_ACCEPT_SHUTDOWN;
ServiceStatus.dwWin32ExitCode = 0;
ServiceStatus.dwServiceSpecificExitCode = 0;
ServiceStatus.dwCheckPoint = 0;
ServiceStatus.dwWaitHint = 0;
hStatus = RegisterServiceCtrlHandler( _T("MemoryStatus_new_3"), (LPHANDLER_FUNCTION)ControlHandler);
if (hStatus == (SERVICE_STATUS_HANDLE)0)
{
// Registering Control Handler failed
WriteToLog("Registering Control Handler failed\n");
return;
}
// We report the running status to SCM.
ServiceStatus.dwCurrentState = SERVICE_RUNNING;
SetServiceStatus (hStatus, &ServiceStatus);
// Initialize Service
startSvc();
return;
}
void startSvc()
{
STARTUPINFO si;
PROCESS_INFORMATION pi;
ZeroMemory(&pi, sizeof(pi));
ZeroMemory(&si, sizeof(si));
si.cb = sizeof(si);
// Start the child process
if(CreateProcess(_T("C:\\Program Files\\Source Insight 3\\Insight3.exe"), _T(""), NULL, NULL, FALSE, 0, FALSE, NULL, &si, &pi))
{
CloseHandle(pi.hProcess);
CloseHandle(pi.hThread);
}
else
{
hProcess = GetCurrentProcess();//get current process
TerminateProcess(hProcess,0); //close process
}
}
如果CreateProcess()失敗,爲什麼你的進程會自殺?嘗試刪除該行爲並查看異常是否消失。 – CoreTech
非常感謝您的意見,但刪除後仍然失敗。並且當我僅在main()函數中調用startSvc()時,它會成功,但如果通過服務調用它,則失敗... 「wins.exe中0x00000000處未處理的異常:0xC0000005:訪問衝突讀取位置0x00000000」。 – user1482337
你的代碼真的有這條線嗎?它不應該使用額外的* *編譯:ServiceTable [0] .lpServiceProc =(LPSERVICE_MAIN_FUNCTION)* * ServiceMain * *; – CoreTech