3

I'm developping an app which needs to run a command as root user so I use:

process = Runtime.getRuntime().exec("su");

Then I launch te process with:

os = new DataOutputStream(process.getOutputStream());

os.writeBytes("tcpdump\n");

When I need the process to finish os.writeBytes("exit\n"); doesn't work and process.waitFor(); get's blocked and the process doesn't finish. I need to send Control-C to the process to stop it but I don't know how I could do it.

Thanks.

Jimix
  • 1,539
  • 3
  • 15
  • 20

3 Answers3

1

On his github, Chainfire provides a sample implementation of a Shell class that you can use to execute commands as root. The class handles all the tasks using Threads so you can be sure that the command will not block even if it does not return.

Code Snippet:

if(Shell.SU.available()){
   Shell.SU.run("commandAsRoot"); //Command executed as root
else{
   System.out.println("su not found");

Or if you are certain that the su binary is available, you can just run your commands (commented line) and skip the check.

Source: How-To SU

cnexus
  • 454
  • 1
  • 3
  • 14
1

Find out whether the API has a kill() method somewhere and use that method to send the SIGINT signal to the target process.

zvrba
  • 24,186
  • 3
  • 55
  • 65
0

Add this at the location you want a ctrl-c signal to be issued.

Process interrupt = Runtime.getRuntime().exec("su");
ios = new DataOutputStream(interrupt.getOutputStream());

ios.writeBytes("pkill -SIGINT tcpdump");
ios.flush();
ios.close();
interrupt.waitFor();

If there are multiple processes running by the name of tcpdump and you need to be selective, find out the specific process id using pidof and grep commands. Accept the answer if it worked for you. Let me know in comments if you are facing issues.

Praveen
  • 393
  • 4
  • 10