Skip to content

Instantly share code, notes, and snippets.

@enthus1ast
Last active October 19, 2018 19:47
Show Gist options
  • Save enthus1ast/0529b06aae315b5312e737ec405ef944 to your computer and use it in GitHub Desktop.
Save enthus1ast/0529b06aae315b5312e737ec405ef944 to your computer and use it in GitHub Desktop.
type ServiceMain = proc(gSvcStatus: SERVICE_STATUS)
proc wrapServiceMain(mainProc: ServiceMain): LPSERVICE_MAIN_FUNCTION {.closure.} =
## wraps a nim proc in a LPSERVICE_MAIN_FUNCTION
return proc(dwArgc: DWORD, lpszArgv: LPTSTR) {.stdcall.} =
gSvcStatusHandle = RegisterServiceCtrlHandler(
SERVICE_NAME,
svcCtrlHandler
)
gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS
gSvcStatus.dwServiceSpecificExitCode = 0
reportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0)
mainProc(gSvcStatus) # call the wrapped proc ## <------------ This failes with `illegalCapture`
reportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0) # we have to report back when we stopped!
when isMainModule:
import times, os
proc serviceMain(gSvcStatus: SERVICE_STATUS) =
## a service main
## use gScvStatus to check if we should stop periodically!
var fh = open("C:/servicelog.txt", fmAppend)
fh.write("SERVICE STARTED\n")
fh.flushFile()
while gSvcStatus.dwCurrentState == SERVICE_RUNNING:
reportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0)
fh.write($epochTime() & "\n")
fh.flushFile()
sleep(1_000)
fh.write("SERVICE CLOSED BY MANAGER!\n")
fh.flushFile()
reportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0) # we have to report back when we stopped!
var wrapped = wrapServiceMain(serviceMain)
Solution:
[...]
template wrapServiceMain(mainProc: ServiceMain): LPSERVICE_MAIN_FUNCTION =
## wraps a nim proc in a LPSERVICE_MAIN_FUNCTION
proc foo(dwArgc: DWORD, lpszArgv: LPTSTR) {.stdcall.} =
gSvcStatusHandle = RegisterServiceCtrlHandler(
SERVICE_NAME,
svcCtrlHandler
)
gSvcStatus.dwServiceType = SERVICE_WIN32_OWN_PROCESS
gSvcStatus.dwServiceSpecificExitCode = 0
reportSvcStatus(SERVICE_RUNNING, NO_ERROR, 0)
mainProc(gSvcStatus) # call the wrapped proc
reportSvcStatus(SERVICE_STOPPED, NO_ERROR, 0) # we have to report back when we stopped!
foo
[...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment