Execute a shell command using processBuilder and interact with it

后端 未结 1 1258
忘了有多久
忘了有多久 2021-01-02 20:43

I\'m trying to create a program allowing me to execute a command through a terminal (which is OmxPlayer for raspberry pi if you want to know) with arguments, but i\'d want t

相关标签:
1条回答
  • 2021-01-02 21:20

    "(actually it's "ls" but it should work exactly the same way)"

    No, it is not. Because the 'ls' process returns immediately after its call. Your omixplayer at the other hand is interactive and will accept commands at runtime.

    What you have to do:

    • create a class which implements Runnable and let this class read from the prs.getInputStream(). You will need this because the .read() will block and wait for new data to read.

    • get the OutputStream of the Process object (prs.getOutputStream()). Everything you write to the OutputStream will be read from your omixplayer. Don't forget to flush the OutputStream and every command needs an "\n" at the end to be executed.

    Like that:

    public class TestMain {
        public static void main(String a[]) throws InterruptedException {
    
            List<String> commands = new ArrayList<String>();
            commands.add("telnet");
            commands.add("www.google.com");
            commands.add("80");
            ProcessBuilder pb = new ProcessBuilder(commands);
            pb.redirectErrorStream(true);
            try {
    
                Process prs = pb.start();
                Thread inThread = new Thread(new In(prs.getInputStream()));
                inThread.start();
                Thread.sleep(2000);
                OutputStream writeTo = prs.getOutputStream();
                writeTo.write("oops\n".getBytes());
                writeTo.flush();
                writeTo.close();
    
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    
    class In implements Runnable {
        private InputStream is;
    
        public In(InputStream is) {
            this.is = is;
        }
    
        @Override
        public void run() {
            byte[] b = new byte[1024];
            int size = 0;
            try {
                while ((size = is.read(b)) != -1) {
                    System.err.println(new String(b));
                }
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    
        }
    }
    

    P.S.: Keep in mind this example is quick an dirty.

    0 讨论(0)
提交回复
热议问题