linux下统计网络字节数

本文介绍了一个C++程序,该程序通过类实现字节数的累加,并使用信号处理来定期展示当前的字节统计信息。程序采用模块化的编码方式,包括信号处理函数、字节累加函数及主函数等部分。
#include <iostream>
#include <stdint.h>
#include <unistd.h>
#include <signal.h>

using namespace std;

#define CARRY_BIT (1024)
#define NEED_CARRY(x) (x > CARRY_BIT)?(true):(false)

#define CARRY(x, y) do {    \
    if (NEED_CARRY(x)) {    \
        y = y + 1;          \
        x = 0;              \
    }                       \
} while (0)

class Count {
    public:
        Count()
            :bytes_(0), KBytes_(0), MBytes_(0), GBytes_(0), TBytes_(0)
        {
        }
        void Add(uint64_t bytes)
        {
            bytes_ += bytes;
            CARRY(bytes_, KBytes_);
            CARRY(KBytes_, MBytes_);
            CARRY(MBytes_, GBytes_);
            CARRY(GBytes_, TBytes_);
        }

        void Show(void)
        {
            cout << TBytes_ << "TB, "
                << GBytes_ << "GB, "
                << MBytes_ << "MB, "
                << KBytes_ << "KB, "
                << bytes_ << "Byte" << endl;
        }

    private:
        uint64_t bytes_;
        uint64_t KBytes_;
        uint64_t MBytes_;
        uint64_t GBytes_;
        uint64_t TBytes_;
};

Count count;

void handle_alarm(int signal)
{
    if (signal == SIGALRM) {
        count.Show();
    }

    alarm(1);
}

void test(void)
{
    signal(SIGALRM, handle_alarm);
    alarm(1);

    while (1) {
        count.Add(1);
    }
}

int main(int argc, char *const argv[])
{
    test();
    return 0;
}

结果:


0TB, 297GB, 492MB, 869KB, 534Byte
0TB, 297GB, 635MB, 995KB, 1003Byte
0TB, 297GB, 778MB, 812KB, 485Byte
0TB, 297GB, 921MB, 880KB, 832Byte
0TB, 298GB, 38MB, 1014KB, 339Byte
0TB, 298GB, 181MB, 123KB, 832Byte
0TB, 298GB, 324MB, 62KB, 1003Byte
0TB, 298GB, 467MB, 216KB, 189Byte
0TB, 298GB, 610MB, 321KB, 102Byte
0TB, 298GB, 753MB, 150KB, 679Byte
0TB, 298GB, 896MB, 332KB, 91Byte
0TB, 299GB, 14MB, 282KB, 154Byte
0TB, 299GB, 157MB, 558KB, 82Byte
0TB, 299GB, 300MB, 571KB, 535Byte
0TB, 299GB, 442MB, 96KB, 613Byte
0TB, 299GB, 584MB, 1021KB, 791Byte
0TB, 299GB, 723MB, 664KB, 195Byte

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值