Code is provided for learning reference. Please read the comments in the code carefully.
Code is provided for learning reference. Please read the comments in the code carefully.
#include "vxWorks.h"
#include "spyLib.h"
#include "stdio.h"
#include "ioLib.h"
#include "stdarg.h"
#include "taskLib.h"
#include "sysLib.h"
#include "string.h"
#define SPYTASKSMAX 100
int data_ana(const char*,...);
/* Function: Detect CPU usage and call data_ana function for processing, finally print the usage on shell, can also redirect to print in other locations, main function can call this function directly
* Input parameters:
* Return value: 0
*/
int CPU_utilization(void)
{
spyLibInit(SPYTASKSMAX);//Initialize spy, maximum number of tasks to spy is SPYTASKSMAX
spyCommon(5,100,(FUNCPTR)data_ana);//This routine collects task activity data and periodically runs spyReport(). Data is collected several times per second, and a report is generated every few seconds. If freq is zero, it defaults to 5 seconds. If ticksPerSec is omitted or zero, it defaults to 100s
return 0;
}
/* Function: Can send udp messages to different ip addresses
* Input parameters: const char* fmtPtn,... This parameter is variable length, all parameter types are const char*, assigned to rbuf in a loop through v1, thus obtaining each line output by the spy function on shell, and after processing the line content, the CPU usage is obtained
* Return value: 0
*/
int data_ana(const char* fmtPtn,...)
{
char rbuf[256];
const char* IDEL = "IDLE";
char percent[50];
int i=0;
int j=0;
int p;
va_list vl;
va_start(vl,fmtPtn);
vsprintf(rbuf,fmtPtn,vl); //Write v1 to string buf according to format fmtptn, obtaining a line of string.
if(strstr(rbuf,IDEL)!= NULL)
/*
The IDLE rate indicates the CPU idle proportion, in the spy output information, there is a line for the idel value, after obtaining this value, subtract it from 100 to get the CPU usage
*/
{
printf("%s\n",rbuf);
for(i=0;(i<256)&&(rbuf[i] != '%');i++)
{
if(rbuf[i]>='0'&&rbuf[i]<='9')
{
percent[j] = rbuf[i];
j++;
}
}
percent[j]='\0';
//printf("CPU free percent= %s \n",percent);
p=atoi(percent);
printf("CPU use percent= %i%%\n",100-p);
}
va_end(vl);
return 0;
}
For more VxWorks resources, please click “Read Original”