0

I was trying to run the following instruction in Android (Java):

 Process p = Runtime.getRuntime().exec("/system/bin/lsof|grep mediaserver");

but I am getting an error if I run the following instruction:

 Process p = Runtime.getRuntime().exec("/system/bin/lsof ");

the file is successfully saved. Can anyone tell what is the error? Actually I want to list and check if media server service is being running or not.

Oriol Roma
  • 329
  • 1
  • 5
  • 9
chiv
  • 165
  • 1
  • 2
  • 15
  • Well, since you are the one getting the error, perhaps you could tell us what the error is. Maybe then we could help you, no? – verdesmarald Aug 27 '12 at 14:12
  • First guess? Since you have to put /system/bin in front of the lsof command, maybe try putting the path to grep in there too? i.e. use /system/bin/lsof | /system/bin/grep mediaserver" or whatever the path to grep is. – billjamesdev Aug 27 '12 at 14:14
  • i am getting the following error W/System.err(345): java.io.IOException: Error running exec(). Command: [/system/bin/lsof|grep, init] Working Directory: null Environment: null – chiv Aug 27 '12 at 14:24

2 Answers2

1

The grep utility may not be installed on your device.

You can check it by trying the following in a console:

> adb shell
$ grep
grep: not found

The last line indicates that this command is not available.

sdabet
  • 18,360
  • 11
  • 89
  • 158
0

The problem is that Runtime.getRuntime().exec(...) does not know how to deal with the shell language. On a Linux / Unix platform you would so something like this:

Process p = Runtime.getRuntime().exec(new String[]{
    "/bin/sh", "-c", "/system/bin/lsof | grep mediaserver"});

However, (apparently) Android doesn't have a command shell / command prompt by default. So either you need to identify and install a suitable shell on your device, or construct the pipeline "by hand"; i.e. by creating a "pipe" file descriptor, and execing the two commands so that lsof writes to the pipe and grep reads from it.

Maybe the answer is to run it like this ...

Process p = Runtime.getRuntime().exec(
        "adb shell /system/bin/lsof | grep mediaserver");

(Try running the "shell ...." part from adb interactively before doing it from Java.)

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216
  • thanks for the reply i am getting error W/System.err(1370): java.io.IOException: Error running exec(). Command: [/bin/sh, -c, /system/bin/lsof | grep init] Working Directory: null Environment: null – chiv Aug 27 '12 at 14:58
  • what is this string for "/bin/sh" – chiv Aug 28 '12 at 12:54