1

If a process is started by current JVM via Runtime.getRuntime().exec(), we can simply access its I/O stream via process.getInputStream() and process.getOutputStream().

But what if a process which is NOT started by current JVM? I do find a solution for Linux here. Is there a cross-platform and packaged API can access streams of other processes?

Firok
  • 269
  • 1
  • 6
  • If you copy the "linux way" in Java, it is possible. You can't steal a stream of a random process, but you can emulate pipes by launching your second JVM from your first. – Sam Aug 07 '23 at 07:53

1 Answers1

2

If you wanted to do that in Java on Linux, you would need to:

  1. find out what the other processes (Linux) process id is. For example, run "ps" as an external command and parse its output to find the PID that you need
  2. Use FileInputStream or FileOutputStream to open the file /proc/<pid>/<n> where <pid> is the PID and <n> is the 0, 1 or 2 (for stdin, stdout or stderr respectively).

Is there a cross-platform and packaged API can access streams of other processes?

AFAIK - No.

I don't know if this even possible to do on Windows. It wasn't possible on older versions of UNIX before the "/proc" filesystem was invented.


For what it is worth, there are better ways to do interprocess communications (IPC) than this (ahem) hack. For example, use IP or Domain sockets (aka named pipes).

Stephen C
  • 698,415
  • 94
  • 811
  • 1,216