Java: popen()-like function?

2020-02-01 01:48发布

This is in the context of a local Processing program. I would like to run an external program to get some data. Is there a popen() or equivalent function I can use?

标签: java popen
3条回答
甜甜的少女心
2楼-- · 2020-02-01 02:19

JDK5 introduced ProcessBuilder for more control over the process generation.

Process process = new ProcessBuilder(command).start()

Be aware of the fact, that internally forkAndExec is invoked, and fork 'makes a copy of the entire parents address space', so that even a little command can lead to OutOfMemoryErrors, when the parent process has big amount of memory space acquired.

see here

查看更多
走好不送
3楼-- · 2020-02-01 02:24

A close friend of popen() is to make a named pipe as input and/or output, like in UNIX:

mknod /tmp/mypipe.12345 p ; sort -o /tmp/mypipe.12345 /tmp/mypipe.12345 &

Then open /tmp/mypipe.12345, write, close, open /tmp/mypipe.12345, read, close. Since a sort cannot write anything until EOF on input, the output open will occur after the input close. The popen() call cannot do this!

For simpler scenarios, the named pipe can just be read or written.

Of course, you still need to spin it off, as in a system(...) call.

You want to remove the named pipe when you are done. On some UNIX systems, /tmp is cleared upon reboot.

/tmp is shared so name collisions are quite possible. You can generate a partly random pipe file name (numeric part of /tmp/mypipe.12345) in Java to generally prevent this. In some systems, Bash creates named pipes in /var/tmp for every <(...) or >(...) use. Unfortunately, it is a bit of a challenge to determine when they can be removed without effect (fuser?)!

查看更多
兄弟一词,经得起流年.
4楼-- · 2020-02-01 02:35
Process process = Runtime.getRuntime().exec("your command");

Then you can read and write the data using the Process streams.

查看更多
登录 后发表回答