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

被折叠的 条评论
为什么被折叠?



