获取执行的shell命令的结果失败/挂起

时间:2010-09-15 10:17:24

标签: android shell iostream

我尝试执行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]  

1 个答案:

答案 0 :(得分:0)

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