简体   繁体   中英

How to kill a process generated through windows cmd line using c#?

I have an windows application in C# which gets Android Logs (LOGCAT) and Android BugReport (BugReport).

To get these logs, i am using bat files with commands like. For Bugreport,

adb bugreport >>C:\User\Desktop\androidUser\bugrep%dt%_%tm%.txt

For LogCat,

 adb logcat -long V >>C:\User\Desktop\androidUser\LogCat%dt%_%tm%.txt

dt and tm are timestamps.

I can run both of this commands at one (With two different buttons in aspx webpage) but if i want to stop only one of them then the problem arise.

The problem is that i can't kill the process using process name as its same for the both tasks. Another thing that i have tried is save the process id while executing the command and kill it but the pid associated while running the task is of cmd, so adb task keeps keeps running and is not killed as i wished.

Look into Process and ProcessStartInfo classes. You can launch applications with arguments which seems to be all you are doing. Can't you sidestep the need of .bat files altoghether? That would make tracking each process independently trivial.

Something along the following lines:

var dt = ....
var tm = ....
var startInfo = new ProcessStartInfo("adb", $"bugreport >>C:\\User\\Desktop\\androidUser\\bugrep{dt}_{tm}.txt");
var bugReportingProcess = Process.Start(startInfo);

Sometimes, arguments are only parsed correctly if quoted:

var startInfo = new ProcessStartInfo("adb", $"\"bugreport >>C:\\User\\Desktop\\androidUser\\bugrep{dt}_{tm}.txt\"");    

And now killing the correct process is easy:

if (!bugReportingProcess.HasExited) bugReportingProcess.Kill();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM