Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get the PID of a process to kill it, without knowing its full name

I'm coding an Android application. Now I'm going to a part where the application should kill a process. But I don't know its full name or its PID. I Know the commands:

android.os.Process.killProcess(Pid)

and

android.os.Process.getUidForName("com.android.email")

But my problem is that I don't know the full name of the process.

It's an native code process, so not something like com.something.something

The process is /data/data/com.something.something/mybinary

but it's running with commands like

/data/data/com.something.something/mybinary -a 123 -b 456

because of this I can't use

android.os.Process.getUidForName("/data/data/com.something.something/mybinary")
like image 408
user1114653 Avatar asked Dec 24 '11 14:12

user1114653


2 Answers

your process name is '/data/data/com.something.something/mybinary' first get process id of the native process running by parsing output of top and then use android.os.Process.killProcess(Pid)

             import org.apache.commons.exec.*;
             import java.io.IOException;
        public class NativeKillerRunnable implements Runnable {
             private static final Logger logger = LoggerFactory.getLogger(NativeKillerRunnable.class);
          @Override
                public void run() {
        String commandtoexec = "top -n 1 -m 100";
        CommandLine cmdLine = CommandLine.parse(commandtoexec);
       DefaultExecutor executor = new DefaultExecutor();
        try {
           PumpStreamHandler psh = new PumpStreamHandler(new LogOutputStream() {
            @Override
            protected void processLine(String s, int i) {
                s = s.trim();
      //check for name of your binary process 
                if(s.contains("mybinary"))
                {
                    String[] strings = s.split(" ");
                    android.os.Process.killProcess(Integer.parseInt(strings[0]));
                    logger.info("killed mybinary process with pid = "+strings[0]);
                }
            }
        });
        executor.setStreamHandler(psh);
        executor.execute(cmdLine);
    } catch (ExecuteException executeException) {
        logger.error("caught exception while killing mybinary process "+executeException.getMessage());
    } 
}

}

like image 164
Dheeraj Sachan Avatar answered Oct 12 '22 15:10

Dheeraj Sachan


I got same problem.Finally,I find a method to kill my binary process with android java code. first,write process info to a txt file:

echo `ps | grep /data/data/com.something.something/mybinary` > /sdcard/pid.txt

and then,use java code to read this file,you could get String like:

root 17857 16409 87568 14880 ffffffff aaf0ec68 R /data/data/com.something.something/mybinary

you have got the pid of your process, execute kill command in java.

like image 33
coffee8651 Avatar answered Oct 12 '22 15:10

coffee8651