使用系统调用的 C++ 定时器
本文中,我们将介绍如何使用系统调用在 C++ 中设计一个定时器。我们不会使用任何图形或动画。这里的定时器意味着秒表,它可以对时间进行累加。使用到的系统调用如下 −
sleep(n) − 将帮助程序休眠 n 秒
system() − 通过将命令作为此函数的参数传递来执行系统命令。
示例
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <unistd.h>
using namespace std;
int hrs = 0;
int mins = 0;
int sec = 0;
void showClk() {
system("cls");
cout << setfill(' ') << setw(55) << " TIMER \n";
cout << setfill(' ') << setw(66) << " --------------------------------------\n";
cout << setfill(' ') << setw(29);
cout << "| " << setfill('0') << setw(2) << hrs << " Hours | ";
cout << setfill('0') << setw(2) << mins << " Minutes | ";
cout << setfill('0') << setw(2) << sec << " Seconds |" << endl;
cout << setfill(' ') << setw(66) << " --------------------------------------\n";
}
void systemCallTimer() {
while (true) {
showClk();
sleep(1);
sec++;
if (sec == 60) {
mins++;
if (mins == 60) {
hrs++;
mins = 0;
}
sec = 0;
}
}
}
int main() {
systemCallTimer();
}输出

广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP