Sending a command to java -jar using stdin via / proc / {pid} / fd / 0

I am trying to send a command to the minecraft server jar using / proc / {pid} / fd / 0, but the server does not execute the command.

To reproduce what I'm trying to do, you can do it on a Debian-based machine (possibly in other Linux distributions).

What I use to verify this:

  • Ubuntu 14.04
  • minecraft_server.jar (tested since 1.8)
  • OpenJDK Runtime workspace (installed with jre-headless disabled by default)

First console:

$ java -jar minecraft_server.jar nogui

Answer: [... the server starts and waits for input]

say hi

Answer: [19:52:23] [Server thread / INFO]: [Server] hello

Second console:

Now, when I switch to the second console, with the server still running in the first, I write:

echo "say hi2" >> /proc/$(pidof java)/fd/0

, . "say hi2", . , , , , .

? , /proc/ {pid}/fd/0 java jar?

, - Java-, , - - , ..

, , -f - , , , . , , - .

. - , , .

+4
2

Java. , , .

:

console1:

 $ cat

, , "return".

Console2: cat. , NNN. :

$ echo Something > /proc/NNN/fd/0

1. "-", .

?

$ ls -l /proc/NNN/fd

. , 0 stdin, 1 stdout 2 stderr, , (pts), , .

, , , , . , , ( ). .

/proc , :

/proc/[pid]/fd/

, , , . , 0 , 1 , 2 .. .

, , . ( , ) , , . - , - .

, fifo - .

fifo, :

$ mkfifo myfifo

Java:

$ java -jar minecraft_server.jar nogui < myfifo

.

$ cat > myfifo

. . , .

. fifo, , EOF .

+4

, "", . , .

#! /bin/bash

# tac prints a file in reverse order (tac -> cat)
cmd="tac"

# create fifo called pipe
mkfifo pipe
# open pipe on the current process file descriptor 3
exec 3<>pipe

bash -c "
    # child process inherits all file descriptors. So cmd must be run from a sub-
# process. This allows us to close fd so cmd does not inherit fd 3, but allow fd 3
# to remain open on parent process.
    exec 3>&-
    # start your cmd and redirect the named pipe to its stdin
    $cmd < pipe
" &

# write data to pipe
echo hello > pipe
echo world > pipe

# short wait before tidy up
sleep 0.1
# done writing data, so close fd 3 on parent (this) process
exec 3>&-
# tac now knows it will receive no more data so it prints its data and exits
# data is unbuffered, so all data is received immediately. Try `cat` instead to see.
# clean up pipe
rm pipe
0

All Articles