libvirt API简单小程序
1、程序代码如下
#include<stdio.h>
#include<libvirt/libvirt.h> int getDomainInfo(int id) {
virConnectPtr conn = NULL;
virDomainPtr dom = NULL;
virDomainInfo info; conn = virConnectOpenReadOnly(NULL);
if (conn == NULL) {
fprintf(stderr, "Failed to connect to hypervisor\n");
return 1;
}
dom = virDomainLookupByID(conn, id);
if (dom == NULL) {
fprintf(stderr, "Failed to find Domain %d\n", id);
virConnectClose(conn);
return 1;
}
if (virDomainGetInfo(dom, &info) < 0) {
fprintf(stderr, "Failed to get information for Domain %d\n", id);
virDomainFree(dom);
virConnectClose(conn);
return 1;
}
printf("Domain ID: %d\n", id);
printf(" vCPUs: %d\n", info.nrVirtCpu);
printf(" maxMem: %d KB\n", info.maxMem);
printf(" memory: %d KB\n", info.memory); if (dom != NULL){
virDomainFree(dom);
}
if (conn != NULL){
virConnectClose(conn);
}
return 0;
}
int main(int argc, char **argv)
{
int dom_id = 3;
printf("-----Get domain info by ID via libvirt C API -----\n");
getDomainInfo(dom_id);
return 0;
}
2、程序编译并运行,运行结果如图1所示
gcc dominfo.c -o dominfo -lvirt
./dominfo
-lvirt指定程序链接时的共享库,在本文实验环境中依赖的共享库文件路径为/usr/lib/libvirt.so
图 1
将运行结果和virsh的运行的结果相比较,virsh的结果如图2所示
图 2