Jackzz
Jackzz

Reputation: 1467

Unable to start a C++ Windows Service

I tried creating a Windows service in C++ using this code sample on MSDN. I opened the solution file in Visual Studio 2013 as admin. The build was successful. Then I installed the service, as per the description provided with the code sample, from a command prompt opened as administrator. The service is now shown in the Services tool in my system. However, when I try to start the service, I get error 5: Access is denied.

The output of sc qc CppWindowsService is as follows:

    [SC] QueryServiceConfig SUCCESS

    SERVICE_NAME: CppWindowsService
    TYPE               : 10  WIN32_OWN_PROCESS
    START_TYPE         : 3   DEMAND_START
    ERROR_CONTROL      : 1   NORMAL
    BINARY_PATH_NAME   : C:\Users\Aaa\Documents\CppWindowsService\C++\Debug\CppWindowsService.exe
    LOAD_ORDER_GROUP   :
    TAG                : 0
    DISPLAY_NAME       : CppWindowsService Sample Service
    DEPENDENCIES       :
    SERVICE_START_NAME : NT AUTHORITY\LocalService

Why does this happen, and how can I fix it?

Upvotes: 2

Views: 2187

Answers (2)

Harry Johnston
Harry Johnston

Reputation: 36348

Because the executable file is in your personal Documents folder, the local service account doesn't have access to it.

The easiest resolution would be to change the permissions on the Debug folder to give SERVICE read and execute access, with inheritance enabled. From the command line:

icacls Debug /grant SERVICE:(OI)(CI)(RX)

(Because Windows does not do traverse checking in the default configuration, you do not need to change the permissions for the parent folders.)

Another option is to copy the executable file to a public location (such as inside Program Files) and install it there, but you then have to remember to manually update the copy each time you recompile.

Edit: yet another option, as you suggest, is to change the account to local system so that the service is running with administrative privileges. Best practice is to run services with the least privilege necessary, but at this stage it doesn't matter much.

Upvotes: 1

Jackzz
Jackzz

Reputation: 1467

The comment provided by @Pumkko helped to solve the issue... The service account was specified as LocalService (#define SERVICE_ACCOUNT L"NTAUTHORITY\\LocalService"). From here:

The Local Service account didn't have permissions to the output .exe file, and this was why the error was occuring.

I changed the account type to LocalSystem (#define SERVICE_ACCOUNT L"LocalSystem") and now my service can be started.

Thankyou @Pumkko and @Harry Johnston.

Upvotes: 0

Related Questions