Wednesday, March 30, 2011

User Variable's value in environment variables is not getting during runtime while running jar application from window service?

Hi All :
I have used a method "System.getenv();" to get a value of user defined environment variable in jar application. I have made the jar application to run from window service. But when i try to start the service, it is not getting user defined environment variable's value and showing null pointer exception. I have tried with System variable name in "System.getenv("JAVA_HOME");" method, its working fine by getting the respective value. What is the error with User variable in envirinment variables. Should i do anything in the code?

From stackoverflow
  • Windows services run on behalf of the system, not a particular user. I believe you can configure the service to run as a specific user, at which point you may get the relevant environment variable - but it would be a lot better to configure the application with a properties file or something similar.

  • I confirm that Windows service runs by default as "Local System Account", which does not access user environment.

    You can rather use a user account for the service to Log On.

    alt text

    But be aware that your service will not be aware of environment variable change until your computer reboot! (See This Microsoft technote or this SO question):

    [your service] will inherit its environment from the Services.exe process.
    The Services.exe process receives the environment settings for the Local System account when Windows starts.
    Because the Services.exe process does not use Windows Messaging, when it receives messages that indicate that a value has changed after Windows starts, the Services.exe process does not update its environment settings.
    You cannot force a service that is running to acknowledge a dynamic change to the environment of the Local System account.

    That may not be a problem for JAVA_HOME (which does not change often), but could be for other dynamically set environment variable.


    If this becomes an issue (like, for instance, if you can not start your service with a given user account), you could embed in your java program a run as command in order to query the registry and get the current value of your environment variable

      String  commands [] = new String [] {
        "CMD.EXE",
        "/C",
        "RUNAS   /savecred /user:" 
        + username 
        + " " + "regedit.exe"
      };
    
      Runtime.getRuntime().exec(commands);
    

    with username = the login of the user currently connected (if nobody is connected, this all section of your program based on USER environment variables needs to be skipped)

    You will then be able to query the window registry, reading directly the "User variables" stored in it (they are kept in HKEY_CURRENT_USER\Environment).

  • A windows service gets the user environment of the user the service runs as.

0 comments:

Post a Comment