From ArchWiki
Revision as of 18:25, 7 May 2012 by Synchronicity (talk | contribs) (Starting QEMU virtual machines on boot)
Jump to navigation Jump to search

This template has only maintenance purposes. For linking to local translations please use interlanguage links, see Help:i18n#Interlanguage links.

Local languages: Català – Dansk – English – Español – Esperanto – Hrvatski – Indonesia – Italiano – Lietuviškai – Magyar – Nederlands – Norsk Bokmål – Polski – Português – Slovenský – Česky – Ελληνικά – Български – Русский – Српски – Українська – עברית – العربية – ไทย – 日本語 – 正體中文 – 简体中文 – 한국어

External languages (all articles in these languages should be moved to the external wiki): Deutsch – Français – Română – Suomi – Svenska – Tiếng Việt – Türkçe – فارسی

From the QEMU about page,

QEMU is a generic and open source machine emulator and virtualizer.

When used as a machine emulator, QEMU can run OSes and programs made for one machine (e.g. an ARM board) on a different machine (e.g. your own PC). By using dynamic translation, it achieves very good performance.

When used as a virtualizer, QEMU achieves near native performances by executing the guest code directly on the host CPU. QEMU supports virtualization when executing under the Xen hypervisor or using the KVM kernel module in Linux. When using KVM, QEMU can virtualize x86, server and embedded PowerPC, and S390 guests.

Difference between qemu and qemu-kvm

Depending on your needs, you can choose either to install upstream qemu or qemu-kvm from the official repositories.

KVM (Kernel Virtual Machine) is a Linux kernel module that allows a user space program to utilize the hardware virtualization features of various processors. Today, it supports recent Intel and AMD processors (x86 and x86_64), PPC 440, PPC 970, and S/390 processors.

QEMU can make use of KVM when running a target architecture that is the same as the host architecture. For instance, when running qemu-system-x86 on an x86 compatible processor, you can take advantage of the KVM acceleration - giving you benefit for your host and your guest system.

Not all processors support KVM. You will need an x86-based machine running a recent ( >= 2.6.22 ) Linux kernel on an Intel processor with VT-x (virtualization technology) extensions or an AMD processor with SVM (Secure Virtual Machine) extensions (also called AMD-V). Xen has an (outdated) list of compatible processors. For Intel processors, see also the Intel® Virtualization Technology List.

Installing QEMU

To install the machine emulator version (normal QEMU), install the qemu package.

To install the KVM version (please see the KVM article for more details), install the qemu-kvm package.

Choosing Windows version

QEMU can run any version of Windows. However, 98, Me and XP will run at quite a low speed. You should choose either Windows 95 or Windows 2000. Surprisingly, 2000 seems to run faster than 98. The fastest one is 95, which can from time to time make you forget that you are running an emulator :)

If you own both Win95 and Win98/WinME, then 98lite (from http://www.litepc.com) might be worth trying. It decouples Internet Explorer from operating system and replaces it with original Windows 95 Explorer. It also enables you to do a minimal Windows installation, without all the bloat you normally cannot disable. This might be the best option, because you get the smallest, fastest and most stable Windows this way.

Creating the hard disk image

To run QEMU you will probably need a hard disk image. This is a file which stores the contents of the emulated hard disk.

Use the command:

qemu-img create -f qcow2 win.qcow 4G

to create the image file named "win.qcow". The "4G" parameter specifies the size of the disk - in this case 4 GB. You can use suffix M for megabytes (for example "256M"). You should not worry too much about the size of the disk - the qcow2 format compresses the image so that the empty space does not add up to the size of the file.

Preparing the installation media

The installation CD-ROM/floppy should not be mounted, because QEMU accesses the media directly. It is a good idea to dump CD-ROM and/or floppy to a file, because it both improves performance and does not require you to have direct access to the devices (that is, you can run QEMU as a regular user). For example, if the CD-ROM device node is named /dev/cdrom, you can dump it to a file with the command:

dd if=/dev/cdrom of=win98icd.iso

Do the same for floppies:

dd if=/dev/fd of=win95d1.img

When you need to replace floppies within QEMU, just copy the contents of one floppy over another. For this reason, it is useful to create a special file that will hold the current floppy:

touch floppy.img

Installing the operating system

This is the first time you will need to start the emulator. One thing to keep in mind: when you click inside the QEMU window, the mouse pointer is grabbed. To release it press Template:Keypress.

If you need to use a bootable floppy, run QEMU with:

qemu -cdrom [[cdrom''image]] -fda [[floppy''image]] -boot a [[hd_image]]

or if you are on a x86_64 system (will avoid many problems afterwards):

qemu-system-x86_64 -cdrom [[cdrom''image]] -fda [[floppy''image]] -boot a [[hd_image]]

If your CD-ROM is bootable or you are using ISO files, run QEMU with:

qemu -cdrom [[cdrom''image]] -boot d [[hd''image]]

or if you are on a x86_64 system (will avoid many problems afterwards):

qemu-system-x86_64 -cdrom [[cdrom''image]] -boot d [[hd''image]]

Now partition the virtual hard disk, format the partitions and install the OS.

A few hints:

  1. If you are using Windows 95 boot floppy, then choosing SAMSUNG as the type of CD-ROM seems to work
  2. There are problems when installing Windows 2000. Windows setup will generate a lot of edb*.log files, one after the other containing nothing but blank spaces in C:\WINNT\SECURITY which quickly fill the virtual hard disk. A workaround is to open a Windows command prompt as early as possible during setup (by pressing Template:Keypress) which will allow you to remove these log files as they appear by typing:
del %windir%\security\*.log
Note: According to the official QEMU website, "Windows 2000 has a bug which gives a disk full problem during its installation. When installing it, use the -win2k-hack QEMU option to enable a specific workaround. After Windows 2000 is installed, you no longer need this option (this option slows down the IDE transfers)."

Running the system

To run the system simply type:

qemu [hd_image]

A good idea is to use overlay images. This way you can create hard disk image once and tell QEMU to store changes in external file. You get rid of all the instability, because it is so easy to revert to previous system state :)

To create an overlay image, type:

qemu-img create -b [[base''image]] -f qcow2 [[overlay''image]]

Substitute the hard disk image for base_image (in our case win.qcow). After that you can run qemu with:

qemu [overlay_image]

or if you are on a x86_64 system:

qemu-system-x86_64 [overlay_image]

and the original image will be left untouched. One hitch, the base image cannot be renamed or moved, the overlay remembers the base's full path.

Moving data between host and guest OS

If you have servers on your host OS, they will be accessible with the IP address without any further configuration. So you could just FTP, SSH, etc. to from Windows to share data, or if you would like, you can use Samba.


QEMU supports Samba which allows you to mount host directories during the emulation. It seems that there is an incompatibility with Samba 3.x. and some versions of QEMU. But at least with a current snapshot of QEMU it should be working.

First, you need to have a working Samba installation. Then add the following section to your smb.conf:

   comment = Temporary file space
   path = /tmp
   read only = no
   public = yes

Now start QEMU with:

qemu [hd_image] -smb qemu

Then you should be able to access your host's Samba server with the IP address If you are running Win9x as a guest OS, you may need to add smbserver

to C:\Windows\lmhosts (Win9x has Lmhosts.sam as a SAMple, rename it!).

Mounting the hard disk image - raw image

Fortunately there is a way to mount the hard disk image with a loopback device. Login as root, make a temporary directory and mount the image with the command:

mount -o loop,offset=32256 [hd_image] [tmp_dir]

Now you can copy data in both directions. When you are done, umount with:

umount [hd_image]

The drawback of this solution is that you cannot use it with qcow images (including overlay images). So you need to create you images without \"-f qcow\" option.

Tip: Create a second, raw hard drive image. This way you will be able to transfer data easily and use qcow overlay images for the primary drive.
Warning: Never run QEMU while the image is mounted!

Mounting qcow2 image

You may mount a qcow2 image using qemu-nbd. See [Wikibooks].

Using any real partition as the single primary partition of a hard disk image

Sometimes, you may wish to use one of your system partition from within QEMU (for instance, if you wish booting both your real machine or QEMU using a given partition as root). You can do this using software RAID in linear mode (you need the linear.ko kernel driver) and a loopback device: the trick is to dynamically prepend a master boot record (MBR) to the real partition you wish to embed in a QEMU raw disk image.

Suppose you have a plain, unmounted /dev/hdaN partition with some filesystem on it you wish to make part of a QEMU disk image. First, you create some small file to hold the MBR:

dd if=/dev/zero of=/path/to/mbr count=32

Here, a 16 KB (32 * 512 bytes) file is created. It is important not to make it too small (even if the MBR only needs a single 512 bytes block), since the smaller it will be, the smaller the chunk size of the software RAID device will have to be, which could have an impact on performance. Then, you setup a loopback device to the MBR file:

losetup -f /path/to/mbr

Let's assume the resulting device is /dev/loop0, because we would not already have been using other loopbacks. Next step is to create the "merged" MBR + /dev/hdaN disk image using software RAID:

 modprobe linear
 mdadm --build --verbose /dev/md0 --chunk=16 --level=linear --raid-devices=2 /dev/loop0 /dev/hdaN

The resulting /dev/md0 is what you will use as a QEMU raw disk image (do not forget to set the permissions so that the emulator can access it). The last (and somewhat tricky) step is to set the disk configuration (disk geometry and partitions table) so that the primary partition start point in the MBR matches the one of /dev/hdaN inside /dev/md0 (an offset of exactly 16 * 512 = 16384 bytes in this example). Do this using fdisk on the host machine, not in the emulator: the default raw disc detection routine from QEMU often results in non kilobyte-roundable offsets (such as 31.5 KB, as in the previous section) that cannot be managed by the software RAID code. Hence, from the the host:

 fdisk /dev/md0

Press Template:Keypress to enter the expert menu. Set number of 's'ectors per track so that the size of one cylinder matches the size of your MBR file. For two heads and a sector size of 512, the number of sectors per track should be 16, so we get cylinders of size 2x16x512=16k.

Now, press Template:Keypress to return to the main menu.

Press Template:Keypress and check that the cylinder size is now 16k.

Now, create a single primary partition corresponding to /dev/hdaN. It should start at cylinder 2 and end at the end of the disk (note that the number of cylinders now differs from what it was when you entered fdisk.

Finally, 'w'rite the result to the file: you are done. You know have a partition you can mount directly from your host, as well as part of a QEMU disk image:

 qemu -hdc /dev/md0 [...]

You can of course safely set any bootloader on this disk image using QEMU, provided the original /dev/hdaN partition contains the necessary tools.

Optimizing Windows 9X CPU usage

Windows 9X uses an idle loop instead of the HLT (halt) instruction. Consequently, the emulator will consume all CPU resources when running Windows 9X guests -- even if no work is being done. This only applies to DOS and DOS-based Windows versions (3.X, 95/98/ME) -- NT-based and later Windows versions are not affected.

To resolve this issue, install Rain, Waterfall or CpuIdle in the Windows 9X guest. (Rain might be preferred because it does only what is needed -- replacing the idle loop with the HLT instruction -- and nothing more.)

See Tutorial: Windows 95/98 guest OSes for more information.

Using the Kernel-based Virtual Machine

KVM is a full virtualization solution for Linux on x86 hardware containing virtualization extensions (Intel VT or AMD-V). It consists of a loadable kernel module, kvm.ko, that provides the core virtualization infrastructure and a processor specific module, kvm-intel.ko or kvm-amd.ko. Using KVM, one can run multiple virtual machines running unmodified Linux or Windows images. Each virtual machine has private virtualized hardware: a network card, disk, graphics adapter, etc.

This technology requires an x86 machine running a recent ( >= 2.6.22) Linux kernel on an Intel processor with VT-x (virtualization technology) extensions, or an AMD processor with SVM (Secure Virtual Machine) extensions. It is included in the mainline Linux kernel since 2.6.20 and is enabled by default in the Arch Linux kernel.

Even though QEMU in recent versions ( < 0.15.0) does have initial KVM support (qemu --enable-kvm), it is not recommended to use this, as many KVM-related functions still have not been implemented in upstream QEMU. Instead, you should go for the qemu-kvm package in the official repositories, which is released by the KVM development team and contains all of the latest features (and bugfixes) of KVM userspace. Please refer to the KVM page itself, for more information on using QEMU with KVM on Arch Linux.

Note: qemu >= 0.15.0 has full support for KVM, as the qemu-kvm tree has been completely merged into the upstream qemu tree. There should be no difference between qemu -enable-kvm and qemu-kvm if your version of qemu is >= 0.15.0.

To take advantage of KVM, you simply need a compatible processor (the following command must return something on the screen):

grep -E "(vmx|svm)" --color=always /proc/cpuinfo

And load the appropriate module from your /etc/rc.conf.

  • For Intel® processors add kvm-intel to your MODULES array in /etc/rc.conf
  • for AMD® processors add kvm-amd to your MODULES array in /etc/rc.conf

Also, you will need to add yourself to the group kvm.

gpasswd -a <Your_User_Account> kvm


User-mode networking

By default, without any -net arguments, QEMU will use user-mode networking with a built-in DHCP server. Your virtual machines will be assigned an IP address when they run their DHCP client, and they will be able to access the physical host's network through IP masquerading done by QEMU. This only works with the TCP and UDP protocols, so ICMP, including ping, will not work.

This default configuration allows your virtual machines to easily access the Internet, provided that the host is connected to it, but the virtual machines will not be directly visible on the external network, nor will virtual machines be able to talk to each other if you start up more than one concurrently.

QEMU's user-mode networking can offer more capabilities such as built-in TFTP or SMB servers, or attaching guests to virtual LANs so that they can talk to each other. See the QEMU documentation on the -net user flag for more details.

However, user-mode networking has limitations in both utility and performance. More advanced network configurations require the use of tap devices or other methods.

Tap Networking with QEMU

Basic Idea

Tap devices are a Linux kernel feature that allows you to create virtual "tap" network interfaces that appear as real network interfaces. Packets sent to a "tap" interface are delivered to a userspace program, such as QEMU, that has bound itself to the interface.

QEMU can use tap networking for a virtual machine so that packets sent to the tap interface will be sent to the virtual machine and appear as coming from a network interface (usually an Ethernet interface) in the virtual machine. Conversely, everything that the virtual machine sends through its network interface will appear on the tap interface.

Tap devices are supported by the Linux bridge drivers, so it is possible to bridge together tap devices with each other and possibly with other host interfaces such as eth0. This is desirable if you want your virtual machines to be able to talk to each other, or if you want other machines on your LAN to be able to talk to the virtual machines.

Bridge virtual machines to external network

The following describes how to bridge a virtual machine to a host interface such as eth0, which is probably the most common configuration. This configuration makes it appear that the virtual machine appears directly on the external network, alongside the physical host machine.

Security Warning

Beware that since your virtual machines will appear directly on the external network, this may expose them to attack. You should take all the precautions you normally would take in securing a computer to secure the virtual machine.


We will replace the normal Ethernet adapter with a bridge adapter and bind the normal Ethernet adapter to it. See http://en.gentoo-wiki.com/wiki/KVM#Networking_2 .

1. Make sure that the following packages are installed:

2. Enable IPv4 forwarding by changing net.ipv4.ip_forward = 0 to net.ipv4.ip_forward = 1 in /etc/sysctl.conf.

3. Add bridge and tun to your MODULES array in /etc/rc.conf:

MODULES=( ... bridge tun)

4. Configure your bridge br0 to have your real Ethernet adapter (assuming eth0 for the rest of this guide) in it, in /etc/conf.d/bridges:

 control_br0="setfd br0 0"
Note: This is not described anywhere, but adding the control_br0 line is vital for the bridge to work! For more details look here: FS#16625

5. Change your networking configuration so that you just bring up your real Ethernet adapter without configuring it, allowing real configuration to happen on the bridge interface. In /etc/rc.conf:

 eth0="eth0 up"
 INTERFACES=(eth0 br0)

Remember, especially if you are doing DHCP, it is essential that the bridge comes up AFTER the real adapter, otherwise the bridge will not be able to talk to anything to get a DHCP address!

If you have been giving eth0 a static IP address rather than using DHCP, give br0 similar settings:

br0="br0 netmask broadcast"
INTERFACES=(eth0 br0)
gateway="default gw"

and then in /etc/resolv.conf:

domain lan

6. Install the script that QEMU uses to bring up the tap adapter in /etc/qemu-ifup with root:kvm 750 permissions:

 echo "Executing /etc/qemu-ifup"
 echo "Bringing up $1 for bridged mode..."
 sudo /sbin/ifconfig $1 promisc up
 echo "Adding $1 to br0..."
 sudo /usr/sbin/brctl addif br0 $1
 sleep 2

7. Use visudo to add the following to your sudoers file:

 Cmnd_Alias      QEMU=/sbin/ifconfig,/sbin/modprobe,/usr/sbin/brctl,/usr/bin/tunctl

8. Make sure the user(s) wishing to use this new functionality are in the kvm group. Exit and log in again if necessary.

9. You launch QEMU using the following run-qemu script:

 IFACE=$(sudo tunctl -b -u $USERID)
 printf -v macaddr "52:54:%02x:%02x:%02x:%02x" \
   $(( $RANDOM & 0xff)) $(( $RANDOM & 0xff)) \
   $(( $RANDOM & 0xff))$(( $RANDOM & 0xff))
 qemu-kvm -net nic,macaddr=$macaddr -net tap,ifname="$IFACE" $*
 sudo tunctl -d $IFACE &> /dev/null

Then to launch a VM, do something like this

$ run-qemu -hda myvm.img -m 512 -vga std

10. If you cannot get a DHCP address in the host, it might be because iptables are up by default in the bridge. In that case (from http://www.linux-kvm.org/page/Networking ):

 # cd /proc/sys/net/bridge
 # ls
 bridge-nf-call-arptables  bridge-nf-call-iptables
 bridge-nf-call-ip6tables  bridge-nf-filter-vlan-tagged
 # for f in bridge-nf-*; do echo 0 > $f; done

And if you still cannot get networking to work, see: Linux_Containers#Bridge_device_setup

Host-only networking

If the bridge is given an IP address and traffic destined for it is allowed, but no "real" interface (e.g. eth0) is also connected to the bridge, then the virtual machines will be able to talk to each other and the physical host. However, they will not be able to talk to anything on the external network, provided that you do not set up IP masquerading on the physical host. This configuration is called "host-only" networking by other virtualization software such as VirtualBox.

You may want to have a DHCP server running on the bridge interface to service the virtual network. For example, to use the subnet:

# ifconfig br0
# dnsmasq --interface=br0 --bind-interfaces --dhcp-range=,

Internal networking

If you do not give the bridge an IP address and add an iptables rule to drop all traffic to the bridge in the INPUT chain, then the virtual machines will be able to talk to each other, but not to the physical host or the outside network. This configuration is called "internal" networking by other virtualization software such as VirtualBox. You will either need to assign static IP addresses to the virtual machines, or run a DHCP server on one of them.

Link-level address caveat

By giving the -net nic argument to QEMU, it will, by default, assign a virtual machine a network interface with the link-level address 52:54:00:12:34:56. However, when using bridged networking with multiple virtual machines, it is essential that each virtual machine has a unique link-level (MAC) address on the virtual machine side of the tap device. Otherwise, the bridge will not work correctly, because it will receive packets from multiple sources that have the same link-level address. This problem occurs even if the tap devices themselves have unique link-level addresses because the source link-level address is not rewritten as packets pass through the tap device.

To solve this problem, the last 8 digits of the link-level address of the virtual NICs should be randomized, as in the script above, to make sure that each virtual machine has a unique link-level address.

Networking with VDE2

What is VDE?

VDE stands for Virtual Distributed Ethernet. It started as an enhancement of uml_switch. It is a toolbox to manage virtual networks.

The idea is to create virtual switches, which are basically sockets, and to "plug" both physical and virtual machines in them. The configuration I show here is quite simple; However, VDE is much more powerful than this, it can plug virtual switches together, run them on different hosts and monitor the traffic in the switches. Your are invited to read the documentation of the project.

The advantage of this method is you do not have to add sudo privileges to your users. Regular users should not be allowed to run modprobe.


VDE is in the official repositories, so...

# pacman -S vde2

In my config, I use tun/tap to create a virtual interface on my host. Load the tun module (or add it to your MODULES array in rc.conf):

# modprobe tun

Now create the virtual switch:

# vde_switch -tap tap0 -daemon -mod 660 -group kvm

This line creates the switch, creates tap0, "plugs" it, and allows the users of the group kvm to use it.

The interface is plugged in but not configured yet. Just do it:

# ifconfig tap0 netmask

That is all! Now, you just have to run KVM with these -net options as a normal user:

$ qemu-kvm -net nic -net vde -hda ...

Configure your guest as you would do in a physical network. I gave them static addresses and let them access the WAN using IP forwarding and masquerading on my host:

# echo "1" > /proc/sys/net/ipv4/ip_forward
# iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE

Putting it together

I added this init script to run all this at start-up:


. /etc/rc.conf
. /etc/rc.d/functions
case "$1" in
    stat_busy "Starting VDE Switch"
    vde_switch -tap tap0 -daemon -mod 660 -pidfile $PIDFILE -group kvm
    if [ $? -gt 0 ]; then
        echo "1" > /proc/sys/net/ipv4/ip_forward &&  \
        iptables -t nat -A POSTROUTING -s -o eth0 -j MASQUERADE &&  \
        ifconfig tap0 netmask && \
        stat_done || stat_fail
    stat_busy "Stopping VDE Switch"
    # err.. well, i should remove the switch here...
    $0 stop
    sleep 1
    # Aem.. As long as stop) is not implemented, this just fails
    $0 start
    echo "usage: $0 {start|stop|restart}"  
exit 0

Well, I know it is dirty and could be more configurable. Feel free to improve it. VDE has an rc script too, but I had to make one anyway for the IP forwarding stuff.

Alternative method

If the above method does not work or you do not want to mess with kernel configs, TUN, dnsmasq and iptables you can do the following for the same result.

vde_switch -daemon -mod 660 -group kvm
slirpvde --dhcp --daemon

Then to start the vm with a connection to the network of the host:

kvm -net nic,macaddr=52:54:00:00:EE:03 -net vde whatever.qcow

Improving networking performance

The performance of virtual networking should be better with tap devices and bridges than with user-mode networking or vde, since tap devices and bridges are implemented in-kernel.

In addition, networking performance can be improved by assigning virtual machines a virtio device rather than the default emulation of an e1000 NIC. To do this, add a model=virtio flag to the -net nic option:

-net nic,model=virtio

This will only work if the guest machine has a driver for virtio network devices. Linux does, and the required driver (virtio_net) is included with Arch Linux, but there is no guarantee that virtio networking will work with arbitrary operating systems such as Windows.


QEMU can use the following different graphic outputs: std, cirrus, vmware, qxl, xenfs and vnc. With the vnc option you can run your guest standalone and connect to it via VNC. Other options are using std, vmware, cirrus:


With -vga std you can get a resolution of up to 2560 x 1600 pixels.


Although it is a bit buggy, it performs better than std and cirrus. On the guest, install the VMware drivers:

pacman -S xf86-video-vmware xf86-input-vmmouse

Windows guest

If you use a MS Windows guest, you might want to use RDP to connect to your guest VM. Use: (if you are using a VLAN or are not in the same network as the guest)

qemu -nographic -net user,hostfwd=tcp::5555-:3389

Then connect with either rdesktop or freerdp to the guest, for example:

xfreerdp -g 2048x1152 localhost:5555 -z -x lan

Front-ends for QEMU

There are a few GUI Front-ends for QEMU:

Keyboard seems broken / Arrow keys do not work

Should you find that some of your keys do not work or "press" the wrong key (in particular, the arrow keys), you likely need to specify your keyboard layout as an option. The keyboard layouts can be found in /usr/share/qemu/keymaps.

qemu -k [keymap] [disk_image]

Starting QEMU virtual machines on boot

With libvirt

If a virtual machine is set up with libvirt, it can be configured through the virt-manager GUI to start at host boot by going to the Boot Options for the virtual machine and selecting "Start virtual machine on host boot up".

Custom script

To run QEMU VMs on boot, you can use following rc-script and config.

Config file options
QEMU_MACHINES List of VMs to start
qemu_${vm}_type QEMU binary to call. If specified, will be prepended with /usr/bin/qemu- and that binary will be used to start the VM. I.e. you can boot e.g. qemu-system-arm images with qemu_my_arm_vm_type="system-arm". If not specified, /usr/bin/qemu will be used.
qemu_${vm} QEMU command line to start with. Will always be prepended with -name ${vm} -pidfile /var/run/qemu/${vm}.pid -daemonize -nographic.
qemu_${vm}_haltcmd Command to shutdown VM safely. I am using -monitor telnet:.. and power off my VMs via ACPI by sending system_powerdown to monitor. You can use ssh or some other ways.
qemu_${vm}_haltcmd_wait How much time to wait for safe VM shutdown. Default is 30 seconds. rc-script will kill qemu process after this timeout.

Config file example:

# VMs that should be started on boot
# use the ! prefix to disable starting/stopping a VM

# NOTE: following options will be prepended to qemu_${vm}
# -name ${vm} -pidfile /var/run/qemu/${vm}.pid -daemonize -nographic


qemu_vm1="-enable-kvm -m 512 -hda /dev/mapper/vg0-vm1 -net nic,macaddr=DE:AD:BE:EF:E0:00 \
 -net tap,ifname=tap0 -serial telnet:localhost:7000,server,nowait,nodelay \
 -monitor telnet:localhost:7100,server,nowait,nodelay -vnc :0"

qemu_vm1_haltcmd="echo 'system_powerdown' | nc.openbsd localhost 7100" # or netcat/ncat

# You can use other ways to shutdown your VM correctly
#qemu_vm1_haltcmd="ssh powermanager@vm1 sudo poweroff"

# By default rc-script will wait 30 seconds before killing VM. Here you can change this timeout.

qemu_vm2="-enable-kvm -m 512 -hda /srv/kvm/vm2.img -net nic,macaddr=DE:AD:BE:EF:E0:01 \
 -net tap,ifname=tap1 -serial telnet:localhost:7001,server,nowait,nodelay \
 -monitor telnet:localhost:7101,server,nowait,nodelay -vnc :1"

qemu_vm2_haltcmd="echo 'system_powerdown' | nc.openbsd localhost 7101"


. /etc/rc.conf
. /etc/rc.d/functions

[ -f /etc/conf.d/qemu.conf ] && source /etc/conf.d/qemu.conf

QEMU_DEFAULT_FLAGS='-name ${vm} -pidfile ${PIDDIR}/${vm}.pid -daemonize -nographic'

case "$1" in
    [ -d "${PIDDIR}" ] || mkdir -p "${PIDDIR}"
    for vm in "${QEMU_MACHINES[@]}"; do
       if [ "${vm}" = "${vm#!}" ]; then
         stat_busy "Starting QEMU VM: ${vm}"
         eval vm_cmdline="\$qemu_${vm}"
         eval vm_type="\$qemu_${vm}_type"

         if [ -n "${vm_type}" ]; then

         eval "qemu_flags=\"${QEMU_DEFAULT_FLAGS}\""

         ${vm_cmd} ${qemu_flags} ${vm_cmdline} >/dev/null
         if [  $? -gt 0 ]; then
    add_daemon qemu

    for vm in "${QEMU_MACHINES[@]}"; do
      if [ "${vm}" = "${vm#!}" ]; then
        # check pidfile presence and permissions
        if [ ! -r "${PIDDIR}/${vm}.pid" ]; then

        stat_busy "Stopping QEMU VM: ${vm}"

        eval vm_haltcmd="\$qemu_${vm}_haltcmd"
        eval vm_haltcmd_wait="\$qemu_${vm}_haltcmd_wait"
        vm_pid=$(cat ${PIDDIR}/${vm}.pid)
        # check process existence
        if ! kill -0 ${vm_pid} 2>/dev/null; then
          rm -f "${PIDDIR}/${vm}.pid"

        # Try to shutdown VM safely
        if [ -n "${vm_haltcmd}" ]; then
          eval ${vm_haltcmd} >/dev/null

          while [ "${_w}" -lt "${vm_haltcmd_wait}" ]; do
            sleep 1
            if ! kill -0 ${vm_pid} 2>/dev/null; then
              # no such process
            _w=$((_w + 1))

          # No haltcmd - kill VM unsafely

        if [ -n "${_vm_running}" ]; then
            # kill VM unsafely
            kill ${vm_pid} 2>/dev/null
            sleep 1

        # report status
        if kill -0 ${vm_pid} 2>/dev/null; then
          # VM is still alive
          #kill -9 ${vm_pid}

        # remove pidfile
        rm -f "${PIDDIR}/${vm}.pid"
    rm_daemon qemu

    $0 stop
    sleep 1
    $0 start

    echo "usage: $0 {start|stop|restart}"


See also

A very good QEMU guide by AlienBOB: http://alien.slackbook.org/dokuwiki/doku.php?id=slackware:qemu