I want to write to the stdin of a running process (not Java). How can I get the Process
object or the OutputStream
directly? Runtime.getRuntime()
only helps me spawn new things, not find existing processes.
Asked
Active
Viewed 616 times
0

dimo414
- 47,227
- 18
- 148
- 244
-
your title says Get OutputStream but your description says how to write to the stdin. So which one it is ? – Mauricio Gracia Gutierrez May 19 '15 at 15:27
-
I don't think what you want to do is possible. – GhostCat May 19 '15 at 15:27
-
I think you will need to use shared memory or pipes to communicate between processes. Could be wrong though, maybe others will correct me. – npinti May 19 '15 at 15:28
-
@MauricioGracia In javaland the outputstream of a process is the stdin – May 19 '15 at 15:28
-
1Not exactly. When you create a process yourself, Java creates an output stream and connects its output to the stdin of that process. Java's own stdin is `System.in` which is definitely not an `OutputStream`. – RealSkeptic May 19 '15 at 15:30
-
1@RealSkeptic I think OP means that, from Java's point of view, you're writing to a `Process` `OutputStream` which corresponds to that process' standard input. – Sotirios Delimanolis May 19 '15 at 15:37
-
So this is not really java related at all – Mauricio Gracia Gutierrez May 19 '15 at 17:32
1 Answers
2
This looks possible on Linux, no idea about elsewhere. Searching for "get stdin of running process" revealed several promising looking discussions:
- Writing to stdin of background process
- Write to stdin of a running process using pipe
- Can I send some text to the STDIN of an active process running in a screen session?
Essentially, you can write to the 0th file descriptor of a process via /proc/$pid/fd/0
. From there, you just have to open an OutputStream
to that path.
I just tested this (not the Java part, that's presumably straightforward) and it worked as advertized:
Shell-1 $ cat
This blocks, waiting on stdin
Shell-2 $ ps aux | grep 'cat$' | awk '{ print $2 }'
1234
Shell-2 $ echo "Hello World" > /proc/1234/fd/0
Now back in Shell-1:
Shell-1 $ cat
Hello World
Note this does not close the process's stdin. You can keep writing to the file descriptor.