【问题标题】:Send Control-C to a process running trough Runtime.getRuntime().exec("su");将 Control-C 发送到通过 Runtime.getRuntime().exec("su"); 运行的进程;
【发布时间】:2011-07-02 00:59:54
【问题描述】:

我正在开发一个需要以 root 用户身份运行命令的应用,所以我使用:

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

然后我启动进程:

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

os.writeBytes("tcpdump\n");

当我需要完成进程时,os.writeBytes("exit\n"); 不起作用并且 process.waitFor(); 被阻止并且进程没有完成。我需要将 Control-C 发送到进程以停止它,但我不知道该怎么做。

谢谢。

【问题讨论】:

    标签: android exec root su control-c


    【解决方案1】:

    找出 API 在某处是否有 kill() 方法,并使用该方法将 SIGINT 信号发送到目标进程。

    【讨论】:

    • 确实信息量大的答案...但似乎没有这样的方法。
    【解决方案2】:

    在他的github 上,Chainfire 提供了Shell 类的sample implementation,您可以使用它以root 身份执行命令。该类使用Threads 处理所有任务,因此您可以确保该命令即使没有返回也不会阻塞。

    代码片段:

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

    或者,如果您确定su 二进制文件可用,则只需运行命令(注释行)并跳过检查。

    来源:How-To SU

    【讨论】:

      【解决方案3】:

      将此添加到您希望发出 ctrl-c 信号的位置。

      Process interrupt = Runtime.getRuntime().exec("su");
      ios = new DataOutputStream(interrupt.getOutputStream());
      
      ios.writeBytes("pkill -SIGINT tcpdump");
      ios.flush();
      ios.close();
      interrupt.waitFor();
      

      如果有多个以tcpdump的名字运行的进程,需要选择性,使用pidof和grep命令找出具体的进程id。如果它对您有用,请接受答案。如果您遇到问题,请在 cmets 中告诉我。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-01-21
        • 2017-10-02
        • 2018-02-10
        • 2012-06-14
        • 2021-01-25
        相关资源
        最近更新 更多