0

I am creating simple windows services that calls my batch file,Now i want to stop or terminate the batch file by stopping it to the services.msc,my services stop but the batch file is still active in the background.how can i terminate the batch file in the background i will stop my services.

Thank you in advance.

 using System.ComponentModel;
 using System.Data;
 using System.Diagnostics;
 using System.Linq;
 using System.ServiceProcess;
 using System.Text; 
 using System.Threading.Tasks;

 namespace Myservices
 {
   public partial class Myservices: ServiceBase
   {
    private ProcessStartInfo processListener;
    Process p;
    public Myservices()
    {
        InitializeComponent();
    }

    protected override void OnStart(string[] args)
    {
         processListener = new ProcessStartInfo{

            CreateNoWindow = true,
            UseShellExecute = false,
            FileName = "cmd.exe",
            Arguments = string.Format("/C \"{0}\"", "C:\\myservices\\servceupdate.bat"),
            WindowStyle = ProcessWindowStyle.Hidden,
            RedirectStandardOutput = true,
            RedirectStandardError = true,
            ErrorDialog = false
        };

        p=Process.Start(processListener);
    }

    protected override void OnStop()
    {
        p.Close();//Here my batch file did not terminate.
    }
}
jemz
  • 4,987
  • 18
  • 62
  • 102

2 Answers2

3

Put a title inside you batch file servceupdate.bat, like so:

title servceupdate.bat

Then in the script that you want to use to kill the process, you can run this cmd:

for /f "tokens=2 delims= " %%a in ('tasklist /v ^| findstr "servceupdate.bat"') do taskkill /f /pid %%a
Alex
  • 917
  • 5
  • 11
  • Hi @Alex,is that code you provide will be put inside my c# OnStop()? – jemz Jun 24 '14 at 01:45
  • Not sure, but if you you try to use it without putting it into a batch file, you need to replace the `%%a` to `%a` – Alex Jun 24 '14 at 05:47
  • I tried your code above and put it on the stopper.bat then also i set title on servceupdate.bat,but when i run the stopper.bat it immediately close,the servceupdate.bat did not close,I just manually run my servceupdate.bat so that i can see when it is close. – jemz Jul 31 '14 at 16:21
  • I tried again and it's working now,but can i ask what is the purpose of tokens=2 ? also what is /v ^ will do ?,Thank you – jemz Aug 02 '14 at 08:48
0

You want to use Process Jobs to terminate any child processes when the parent service is stopped.

See

Community
  • 1
  • 1
josh poley
  • 7,236
  • 1
  • 25
  • 25