Search code examples
javawindows-servicesprocessbuilderprocrun

Java: Running batch file with ProcessBuilder when app is registered as Windows Service using Procrun


There is already a 7 year old question with similar title but no accepted answer, hence reposting as my question has additional details.

7 year old question: Running batch file from Java registered as Windows Service using Procrun

My question:

I have following java class:

public static void main(String[] args) {
    ProcessBuilder processBuilder = new ProcessBuilder(new String[] {"C:\\Work\\test.bat"});
    processBuilder.redirectErrorStream(true);   
    Process process = processBuilder.start();
    int exitVal = process.waitFor();
}

when this is run directly from eclipse, test.bat is successfully executed. However, when it is run from service, test.bat does not get executed.

I have installed the jar as a windows service using procrun. Also to validate whether service is correctly installed. I did this:

public static void main(String[] args)
    {
        try {
            DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy hh:mm:ss");
            Calendar calendar = Calendar.getInstance();
            calendar.setTimeInMillis(System.currentTimeMillis());
            File file = new File("C:\\Work\\temp.txt");
            FileUtils.writeStringToFile(file, "hello world "+formatter.format(calendar.getTime()), "UTF-8", false);         
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

and this block of code gets executed from service without any problem. It's just that test.bat does not get executed.

Is ProcessBuilder not allowed from procrun?

EDIT

My test.bat :

start "" cmd /c "echo Hello world!&echo(&pause"


Solution

  • Are you sure that test.bat is not being executed? Please confirm in Task Manager. Be sure to show processes from all users as your batch file will probably be running in the system account.

    Note that your batch file will be launched in the isolated Session 0 and you will not be able to see the command window (and you won't be able to respond to the "pause" command"). You should consider this restriction as you graduate from your test to something real/useful...