【问题标题】:Getting result of executed shell command fails/hangs获取执行的 shell 命令的结果失败/挂起
【发布时间】:2010-09-15 10:17:24
【问题描述】:

我尝试执行 shell 命令,这确实可以正常工作。甚至结果也会回来(如在 LogCat 上所见)。问题是结果的最后一行。每次最后一行出现 readLine() 时(不应该出现, temp 应该为 null),应用程序将永远挂起,并且不会从 readLine 调用中返回。也许你发现了错误。我尝试了 readUTF 和标准 read(),都是同样的问题。是的,该应用获得了 su-rights。

try
                {
                    Process process = Runtime.getRuntime().exec("su");
                    DataOutputStream os = new DataOutputStream(process.getOutputStream());
                    DataInputStream osRes = new DataInputStream(process.getInputStream());
                    for (String single : commands) {
                       os.writeBytes(single + "\n");
                       os.flush();
                       String temp = new String();
                       while(  (temp = osRes.readLine()) != null)
                       {                                      
                           Log.v("NITRO", temp);
                           result2 += temp + "\n";                            
                       }                      
                    }
                    os.writeBytes("exit\n");
                    os.flush();
                    process.waitFor();
                } catch (IOException e)
                {
                    Toast.makeText(Main.this, "Error", Toast.LENGTH_LONG);
                } catch (InterruptedException e)
                {
                    Toast.makeText(Main.this, "Error", Toast.LENGTH_LONG);
                }

这是我在挂起时停止调试器时挂起的 StackTrace:

OSFileSystem.readImpl(int, byte[], int, int) line: not available [native method]    
OSFileSystem.read(int, byte[], int, int) line: 118  
ProcessManager$ProcessInputStream(FileInputStream).read(byte[], int, int) line: 312 
ProcessManager$ProcessInputStream(FileInputStream).read() line: 250 
DataInputStream.readLine() line: 309    
Main$2$1.run() line: 84 
ViewRoot(Handler).handleCallback(Message) line: 587 
ViewRoot(Handler).dispatchMessage(Message) line: 92 
Looper.loop() line: 123 
ActivityThread.main(String[]) line: 4627    
Method.invokeNative(Object, Object[], Class, Class[], Class, int, boolean) line: not available [native method]  
Method.invoke(Object, Object...) line: 521  
ZygoteInit$MethodAndArgsCaller.run() line: 868  
ZygoteInit.main(String[]) line: 626 
NativeStart.main(String[]) line: not available [native method]  

【问题讨论】:

  • 这里在黑暗中拍摄,尝试将exit 移动到while 循环之前?
  • 你应该将你的回复发给@st0le,否则它可能永远不会被看到。
  • @st0le 你是对的,那行得通,谢谢。从一个例子中抓住了这一点,退出是在那个命令之后。但我只想执行一个命令,所以这应该可以。您可以将其发布为答案,我可以接受。

标签: android shell iostream


【解决方案1】:

尝试在 while 循环之前移动出口...您的应用程序永远不会终止,因此 while 循环永远不会结束...。移动 exit 应该会导致应用程序终止,这应该会导致循环获取null...

【讨论】:

    猜你喜欢
    • 2021-07-11
    • 2014-02-20
    • 1970-01-01
    • 2013-05-09
    • 1970-01-01
    • 2016-03-21
    • 1970-01-01
    • 1970-01-01
    • 2011-10-30
    相关资源
    最近更新 更多