Calling a batch file from a windows service

后端 未结 3 1218
孤街浪徒
孤街浪徒 2021-01-26 04:23

I have a service that needs to call a batch when a new file is copied to a directory. I tried using CreateProcess, ShellExecute, ShellExecuteEx

相关标签:
3条回答
  • 2021-01-26 04:42
    Go to run->services.msc->right click on the service ->properties->
    logon->check enable     service to interact with desktop-make it enable
    
    0 讨论(0)
  • 2021-01-26 04:43

    CreateProcess, as shown in the (grossly simplified) example below, is a valid way to execute a batch file from a service.

    STARTUPINFO si = { 0 };
    PROCESS_INFORMATION pi = { 0 };
    si.cb = sizeof(si);
    
    if( !CreateProcessA( NULL,
                         "C:\\test.bat",
                         NULL,
                         NULL,
                         FALSE,
                         0,
                         NULL,
                         NULL,
                         &si,
                         &pi
                       ) )
    {
        char msg[100];
        sprintf( msg, "CreateProcess() failed: %d", GetLastError() );
        OutputDebugStringA( msg );
    }
    

    Logging is key. If the batch file isn't being executed, CreateProcess() will tell you why.

    You mention that the batch file is to be executed "when a new file is copied to a directory." Have you verified that the detection code is working properly? Is the code attempting to execute the batch file actually reached?

    More context would definitely be helpful. Please post the relevant portions of the batch file and service code.

    0 讨论(0)
  • 2021-01-26 04:49

    Make sure that you are using full, absolute paths in your call to CreateProcess since the working directory when the service is running might not be what you think it is (I've made this mistake more times than I'd like to admit).

    See if the behavior changes if you replace the batch file with something simple like:

    @echo TESTING >C:\batch_debug.txt
    

    That should give a better picture of whether the batch file isn't being executed at all or if there's something in the batch file that is causing a problem.

    What kind of a return value are you getting from CreateProcess? If it fails, does GetLastError give you any useful information?

    UPDATE: I think the issue here is that CreateProcess is limited to executables. You can launch a batch file but you have to pass it as a parameter to cmd.exe. You also have to list the parameters separately from the executable name. For example, if the command cmd.exe /c C:\my_batch.bat would normally run your batch file in a new command interpreter instance, the following CreateProcess call should do the same thing:

    CreateProcess("cmd.exe", "/c C:\\my_batch.bat", ...);
    
    0 讨论(0)
提交回复
热议问题