Skip to content

Instantly share code, notes, and snippets.

@airekans
Last active January 1, 2016 19:59
Show Gist options
  • Save airekans/8194409 to your computer and use it in GitHub Desktop.
Save airekans/8194409 to your computer and use it in GitHub Desktop.
Some useful /proc information I can use to check the state of the system.
// This program simply gets the ip for the specified interface.
#include <iostream>
#include <sys/ioctl.h>
#include <net/if.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
using namespace std;
int main(int argc, char** argv)
{
if (argc < 2)
{
cerr << "Usage: " << argv[0] << " IFACE" << endl;
return 0;
}
const char* iface_name = argv[1];
int sock;
struct sockaddr_in soc_addr;
struct ifreq ifr;
if ((sock = socket(AF_INET, SOCK_DGRAM, 0)) == -1)
{
cerr << "Failed to create socket for " << iface_name << endl;
return 1;
}
strncpy(ifr.ifr_name, iface_name, IF_NAMESIZE);
ifr.ifr_name[IFNAMSIZ-1]='\0';
if (ioctl(sock, SIOCGIFADDR, &ifr) < 0)
{
cerr << "Failed to get ip of " << iface_name << endl;
return 1;
}
memcpy(&soc_addr, &ifr.ifr_addr, sizeof(soc_addr));
cout << inet_ntoa(soc_addr.sin_addr) << endl;
close(sock);
return 0;
}
  1. /proc/net/dev records the recv/send bytes and packet number through all the interfaces. The number is accumulated from the booting up, so you can subtract the number from the last check.

  2. /proc/stat contains information about CPU usage. For cpu0 usage in 20s, you can do the following:

    cpu0_line=$(cat /proc/stat | grep cpu0)
    cpu0_total1=$(echo $cpu0_line | awk '{print $2 + $3 + $4 + $5 + $6 + $7 + $8}')
    cpu0_used1=$(echo $cpu0_line | awk '{print $2 + $3 + $4 + $7 + $8}')
    sleep 20
    # calculate again
    cpu0_line=$(cat /proc/stat | grep cpu0)
    cpu0_total2=$(echo $cpu0_line | awk '{print $2 + $3 + $4 + $5 + $6 + $7 + $8}')
    cpu0_used2=$(echo $cpu0_line | awk '{print $2 + $3 + $4 + $7 + $8}')
       
    cpu0_usage_rate=$(python -c "print ($cpu0_used2 - $cpu0_used1) * 100.0 / ($cpu0_total2 - $cpu0_total1)")
  3. ...

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