My preferred way to do this is to connect to the QEMU "monitor" via a UNIX socket. It works well, although the method is very poorly documented.
When you start QEMU, add the -monitor
parameter as follows:
$ qemu-system-i386 [..other params..] -monitor unix:qemu-monitor-socket,server,nowait
qemu-monitor-socket
here is not a keyword, but a host path and filename of your choice to represent the socket on disk. You'll see this file created when QEMU starts.
The options server,nowait
tell QEMU to listen for connections, but start the VM without waiting for a connection.
You can use the socat utility (available from all good repositories) to connect to the socket to type commands to the QEMU monitor prompt:
$ socat -,echo=0,icanon=0 unix-connect:qemu-monitor-socket
QEMU 2.8.1 monitor - type 'help' for more information
(qemu) _
What socat does is connect two arbitrary streams/sockets together. The first parameter -
is a synonym for stdio
, i.e., the console keyboard and output. The couple of options echo=0,icanon=0
make keyboard interaction nicer here by preventing re-echoing of entered commands and enabling Tab completion and arrow keys for history. The final parameter says to connect to the socket file created earlier.
To send a one-shot command to QEMU, echo it thru socat to the UNIX socket:
$ echo "info status" | socat - unix-connect:qemu-monitor-socket
QEMU 2.8.1 monitor - type 'help' for more information
(qemu) info status
VM status: running
(qemu)
$ _
For cleaner output in a script, I also add | tail --lines=+2 | grep -v '^(qemu)'
to filter out the first line and the (qemu)
prompt lines:
$ echo "info status" | socat - unix-connect:qemu-monitor-socket | tail --lines=+2 | grep -v '^(qemu)'
VM status: running
$ _
To shut down the VM as you wanted, useful monitor commands are system_powerdown
, which presses the on/off button of the imaginary machine so it can gracefully shut down, or quit
, which quits QEMU immediately.
A couple of notes:
QEMU also permits -qmp
in place of -monitor
, providing a JSON-based interface; that might be more robust for programmatic control, but I never tried it.
A socket file on disk is always empty. It doesn't store data; it's just an arbitrary handle for programs to open communications.
qemu-system-... -monitor "/dev/ttyMyConsol"
and thanecho "My QemuMonitorCommand" > /dev/ttyMyConsol
and it will make qemu execute the command on that machine? but the only way to control the machine is the qemu-monitor?