开发者

Java: popen()-like function?

This is in the context of a local Processing program. I would like to run an external program to get some data. Is the开发者_开发技巧re a popen() or equivalent function I can use?


Process process = Runtime.getRuntime().exec("your command");

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


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


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?)!

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜