Skip to content

Instantly share code, notes, and snippets.

@dpogorzelski
Last active August 29, 2015 14:16
Show Gist options
  • Save dpogorzelski/b6a3680845692b28124b to your computer and use it in GitHub Desktop.
Save dpogorzelski/b6a3680845692b28124b to your computer and use it in GitHub Desktop.
statsc
#include <stdio.h>
#include <stdlib.h>
#include <netinet/in.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <statsc.h>
#include <fcntl.h>
#include <strings.h>
#include <string.h>
#include <unistd.h>
static int sockfd;
struct sockaddr_in servaddr;
char buf[BUFSIZE];
int main(int argc, char **argv)
{
if(argc != 3) {
fprintf(stderr, "Usage: <ip> <port>");
exit(1);
}
long num_cpu = sysconf(_SC_NPROCESSORS_ONLN);
sockfd = socket(AF_INET, SOCK_DGRAM, 0);
fcntl(sockfd, F_SETFL, O_NONBLOCK);
bzero(&servaddr, sizeof(servaddr));
servaddr.sin_family = AF_INET;
servaddr.sin_addr.s_addr = inet_addr(argv[1]);
servaddr.sin_port = htons(atoi(argv[2]));
while(1) {
cpustats(&num_cpu);
sleep(1);
}
return 0;
}
void cpustats(long *num_cpu)
{
static const char *val_types[] = { "user", "nice", "system",
"idle", "iowait", "irq",
"softirq", "steal", "guest",
"guest_nice" };
unsigned long long int vals[10];
char cpu[8] = { 0 };
static int fd;
char msgs[10][1024];
char *b;
if(fd) {
lseek(fd, 0L, SEEK_SET);
} else {
fd = open("/proc/stat", O_RDONLY, 0);
if(fd == -1) {
perror("/proc/stat");
exit(1);
}
}
read(fd, buf, BUFSIZE - 1);
for(int i = 0; i < *num_cpu; i++) {
sprintf(cpu, "cpu%d", i);
b = strstr(buf, cpu);
if(b) {
sscanf(b,
"%*[a-z0-9] %Lu %Lu %Lu %Lu %Lu %Lu %Lu %Lu %Lu "
"%Lu",
&vals[0],
&vals[1],
&vals[2],
&vals[3],
&vals[4],
&vals[5],
&vals[6],
&vals[7],
&vals[8],
&vals[9]);
for(int8_t i = 0; i < 10; i++) {
sprintf(msgs[i],
"%s.%s:%Lu|g",
cpu,
val_types[i],
vals[i]);
}
send_stat(&msgs);
}
}
}
void send_stat(char (*msgs)[10][1024])
{
size_t size = sizeof((*msgs)) / sizeof((*msgs)[0]);
for(int i = 0; i < size; i++) {
printf("sending: %s\n", (*msgs)[i]);
sendto(sockfd,
(*msgs)[i],
strlen((*msgs)[i]),
0,
(struct sockaddr *)&servaddr,
sizeof(servaddr));
}
}
#ifndef STATS_H_
#define STATS_H_
#define BUFSIZE 8129
void send_stat(char (*msgs)[10][1024]);
void getcpu(long *num_cpu);
#endif /* STATS_H_ */
@dijit
Copy link

dijit commented Mar 7, 2015

Where did you acquire statsc.h from?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment