Not able to run grep command

2019-08-20 03:56发布

I was trying to run the following instruction,

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

In android(java) but I am getting error. if I run 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.

2条回答
狗以群分
2楼-- · 2019-08-20 04:12

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.

查看更多
在下西门庆
3楼-- · 2019-08-20 04:23

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.)

查看更多
登录 后发表回答