最近需要获取虚拟机内CPU的利用率:尝试了多种方法,均不理想,以下是最后利用libvirt-devel开发包,实现一个功能函数。
示例如下:
<span style="font-size:18px;color:#009900;"><strong>#include <stdio.h> #include <unistd.h> #include <string.h> #include <stdlib.h> #include <sys/time.h> #include <libvirt/libvirt.h> #include <libvirt/virterror.h> #define NAME_SIZE 32 struct kvm_state{ char name[NAME_SIZE]; char rflags[16];// running shutoff int mem; //MB int vcpus; float cpu_rate; // long long h_cpu_time; struct timeval h_real_time; }; void s_to_rflags(int state,char*buf){ switch(state){ case 1: // running strcpy(buf,"running"); break; case 2: //blocked strcpy(buf,"block"); break; case 3: // paused strcpy(buf,"paused"); break; case 4: //shut down strcpy(buf,"shut down"); break; case 5: // shut off strcpy(buf,"shut off"); break; case 6: // crashed strcpy(buf,"crashed"); break; case 7: // suspended strcpy(buf,"suspended"); break; default: // none strcpy(buf,"none"); break; } return ; } int GetAllDomainState(struct kvm_state*st){ virConnectPtr conn; virDomainPtr *alldomain=NULL; virDomainInfo domain_info; int num=0,i=0; struct timeval tv; conn = virConnectOpen("qemu:///system"); if (conn == NULL) { fprintf(stderr, "Failed to open connection to qemu+tcp://localhost/system\n"); return 0; } num=virConnectListAllDomains(conn,&alldomain,3);// //st=(struct kvm_state*)malloc(sizeof(struct kvm_state)*num); //memset(st,0,sizeof(struct kvm_state)*num); for(i=0;i<num;i++){ strncpy(st[i].name,virDomainGetName(alldomain[i]),NAME_SIZE); // name //printf(":%s\n",virDomainGetXMLDesc(alldomain[i],1)); virDomainGetInfo(alldomain[i],&domain_info); s_to_rflags(domain_info.state, st[i].rflags);// running state st[i].mem=domain_info.memory/1024;//mem /mb //domain_info.mexMem st[i].vcpus=domain_info.nrVirtCpu;// vcpus st[i].h_cpu_time=domain_info.cpuTime; gettimeofday(&(st[i].h_real_time),NULL); //virDomainFree(alldomain[i]); } sleep(1); for(i=0;i<num;i++){ virDomainGetInfo(alldomain[i],&domain_info); gettimeofday(&tv,NULL); st[i].cpu_rate=((domain_info.cpuTime-st[i].h_cpu_time)/1000.0)/((tv.tv_sec-st[i].h_real_time.tv_sec)*1000000.0 + (tv.tv_usec- st[i].h_real_time.tv_usec)); st[i].cpu_rate=st[i].cpu_rate/st[i].vcpus*100.0; virDomainFree(alldomain[i]); } virConnectClose(conn); return num; } int main(){ int num; struct kvm_state kvm[10]; num=GetAllDomainState(kvm); }</strong></span>