Android: child process (logcat) continues to work after the parent process (application) has died

our Android application starts the logcat shell process and then reads its result for processing. However, when the application stops (for example, when restarting after recompilation during development), the logcat process will continue to work. Here is an example of this behavior:

processes = new ArrayList<Process>(); try { processes.add(Runtime.getRuntime().exec("logcat -v time")); processes.add(Runtime.getRuntime().exec("logcat -v time")); processes.add(Runtime.getRuntime().exec("logcat -v time")); processes.add(Runtime.getRuntime().exec("logcat -v time")); } catch (IOException e) { // oh no! } Runtime.getRuntime().addShutdownHook(new Thread() { public void run() { for (Process p : processes) { p.destroy(); } }; }); 

Add this to the onCreate () method of the test application, start it, and then force-stop it using the settings manager. Baby processes will continue to work, now with parent id 1.

Q How to kill a logcat process initiated by an Android application? It was suggested to use ProcessBuilder, but this was not a solution, and the process would also work ..

In Stop the child process, when the parent process stops , it was suggested to use hookdown - this does not work, as shown above.

Thanks!

+6
source share
1 answer

What you can do is deploy another script, whose sole purpose is to view your Java program. Whenever he dies, kill all your children too.

Fragile example:

 int pid = android.os.Process.myPid(); String script = "while [ -d /proc/" + pid + " ];do sleep 1;done; killall logcat"; Process p = Runtime.getRuntime().exec("/system/bin/sh", "-c", script); 

This assumes that your process does not start as root, thereby only killing its own logcat processes. In your function, you must first kill other processes ( logcat ), and then run p.destroy(); to stop this killer script.

The script above can be improved by removing the use of killall . Instead, get the process IDs of your logcat processes using Reflection ( this answer points to http://www.golesny.de/p/code/javagetpid ) and pass them to kill .

+1
source

Source: https://habr.com/ru/post/943447/


All Articles