简体   繁体   中英

Is it possible to write files to an interactive shell within the declaration of a thread runnable?

I'm attempting to start an interactive shell and then execute commands all with in a runnable thread. I have not been able to even create a new file while in the runnable declaration.

Example 1

if(true){
    Process p = null; 
    try{
        p=Runtime.getRuntime().exec("su");
        BufferredWriter writer = new BufferedWriter(new
        OutputStreamWriter(p.getOutputStream()));
        writer.write("touch /data/local/tmp/file\n");
    }
    catch(Exception e){
    }
}

Example 2

public void createNewThread(){
    thread = new Thread(new Runnable(){
        @Override
        public void run(){
            Process p = null;
            try{
                p = Runtime.getRuntime().exec("su");
                BufferredWriter writer = new BufferedWriter(new
                OutputStreamWriter(p.getOutputStream()));                                                           
                writer.write("touch /data/local/tmp/somefile\n");
            }
            catch(Exception e){
            }
        }
    });
    thread.start(); 
}

In both Example 1 and Example 2 I see can see that have executed su and an interactive shell is running. However file is created in Example 1 but somefile is not created by Example 2. Is there some issue with writing to an interactive shell from with a runnable thread declaration?

This is just a guess, but maybe you need to explicitly writer.flush() ?

Also, you should always close you streams! This will have a bonus effect of automatically call flush() .

try {
    p=Runtime.getRuntime().exec("su");
    BufferredWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));
    writer.write("touch /data/local/tmp/file\n");
} catch(Exception e) {
    // handle exceptions
} finally {
    writer.close(); // this will automatically call writer.flush()
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM