Linux – Sending Text Input to a Detached Screen

gnu-screenlinux

I'm trying to run a minecraft server on my unRAID server.

The server will run in the shell, and then sit there waiting for input. To stop it, I need to type 'stop' and press enter, and then it'll save the world and gracefully exit, and I'm back in the shell. That all works if I run it via telnetting into the NAS box, but I want to run it directly on the box.

this is what I previously had as a first attempt:

#define USER_SCRIPT_LABEL Start Minecraft server
#define USER_SCRIPT_DESCR Start minecraft server. needs sde2 mounted first
cd /mnt/disk/sde2/MCunraid
screen -d -m -S minecraft /usr/lib/java/bin/java -Xincgc -Xmx1024M -jar CraftBukkit.jar

MCunraid is the folder where I have the Craftbukkit.jar and all the world files etc. If I type that screen line in directly, the screen does setup detached and the server launches. If I execute that line from within the script it doesn't seem to set up a screen

for stopping the server, I need to 'type' in STOP and then press enter. My approach was

screen -S minecraft -X stuff "stop $(echo -ne '\r')"

to send to screen 'minecraft' the text s-t-o-p and a carriage return. But that doesn't work, even if I type it directly onto the command line. But if I 'screen -r' I can get to the screen with the server running, then type 'stop' and it shuts down properly.

The server runs well if I telnet in and do it manually, just need to run it without being connected from my remote computer.

Best Answer

I can solve at least part of the problem: why the stop part isn't working. Experimentally, when you start a Screen session in detached mode (screen -d -m), no window is selected, so input later sent with screen -X stuff is just lost. You need to explicitly specify that you want to send the keystrokes to window 0 (-p 0). This is a good idea anyway, in case you happen to create other windows in that Screen session for whatever reason.

screen -S minecraft -p 0 -X stuff "stop^M"

(Screen translate ^M to control-M which is the character sent by the Enter key.)

The problem with starting the session from a script is likely related to unMENU.

Related Question