Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Correctly creating and running a win32 service with file I/O

I've written a very simple service application based on this code example.

The application as part of its normal running assumes there exists a file in the directory it is found, or in its execution path.

When I 'install' the service and then subsequently 'start' the service from the service manager in control panel. The application fails because it can't find the file to open and read from (even though the file is in the same directory as the installed executable).

My question is when a windows service is run, which is the expected running path supposed to be?

When calling 'CreateService' there only seems to be a path parameter for the binary, not for execution. Is there someway to indicate where the binary should be executed from?

I've tried this on windows vista and windows 7. Getting the same issues.

like image 793
Rikardo Koder Avatar asked Dec 20 '22 16:12

Rikardo Koder


1 Answers

Since Windows services are run from a different context than normal user-mode applications, it's best if you don't make any assumptions about working directories or relative paths. Aside from differences in working directories, a service could run using a completely different set of permissions, etc.

Using an absolute path to the file that your service needs should avoid this problem entirely. Absolute paths will be interpreted the same regardless of the working directory, so this should make the working directory of your service irrelevant. There are several ways to go about this:

  1. Hard-code the absolute path - This is perhaps the easiest way to avoid the problem, however it's also the least flexible. This method is probably fine for basic development and testing work, but you probably want something a bit more sophisticated before other people start using your program.
  2. Store the absolute path in an environment variable - This gives you an extra layer of flexibility since the path can now be set to any arbitrary value and changed as needed. Since a service can run as a different user with a different set of environment variables, there are still some gotchas with this approach.
  3. Store an absolute path in the registry - This is probably the most fool-proof method. Retrieving the path from the registry will give you the same result for all user accounts, plus this is relatively easy to set up at install time.
like image 177
bta Avatar answered Dec 24 '22 00:12

bta