Executing an external program using process builder or apache commons exec

ⅰ亾dé卋堺 提交于 2019-12-06 01:03:04

Huh. Using ProcessBuilder should work for your configuration. For example, the following pattern works for me:

ProcessBuilder pb = new ProcessBuilder("/tmp/x");
Process process = pb.start();
final InputStream is = process.getInputStream();
// the background thread watches the output from the process
new Thread(new Runnable() {
    public void run() {
        try {
            BufferedReader reader =
                new BufferedReader(new InputStreamReader(is));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            is.close();
        }
    }
}).start();
// the outer thread waits for the process to finish
process.waitFor();

The program that I'm running is just a script with a whole bunch of sleep 1 and echo lines:

#!/bin/sh
sleep 1
echo "Hello"
sleep 1
echo "Hello"
...

The thread reading from the process spits out a Hello every second or so.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!