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?
3 Answers
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.

- 550
- 8
- 11
-
Could you add a link to ProcessBuilder documentation? – jwfearn Mar 06 '15 at 04:11
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?)!

- 662
- 8
- 25

- 9
- 2