Create a VM file descriptor with KVM_CREATE_VM
ioctl(kvm, KVM_CREATE_VM, 0) returns a new file descriptor for an empty VM. Pass 0 as the machine type on x86, which has no other values.
A VM in KVM is a file descriptor. Everything else, memory regions, vCPUs and interrupt controllers, hangs off it, and closing the last reference to it destroys the machine.
int kvm = open("/dev/kvm", O_RDWR | O_CLOEXEC);
int vm = ioctl(kvm, KVM_CREATE_VM, 0);
if (vm < 0) {
perror("KVM_CREATE_VM");
return 1;
}
printf("vm fd = %d\n", vm);vm fd = 4The fd is 4 because 0, 1 and 2 are the standard streams and 3 is /dev/kvm. The argument is the machine type. On x86 it is always 0, on arm64 it can encode the number of address bits for guest physical addresses, and on s390 it selects between user-controlled and normal VMs. See KVM_CREATE_VM in the KVM API documentation.
The VM belongs to the process that created it. A child created by fork shares the descriptor but cannot use it to run the guest, because KVM binds the VM to the original address space: later calls on it fail with EIO. If you plan to fork, create the VM after the fork, in the process that will run it.