Skip to content

Instantly share code, notes, and snippets.

@Low-power
Created May 10, 2022 12:25
Embed
What would you like to do?
/* Copyright 2015-2022 Rivoreo
Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
"Software"), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:
The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <sys/time.h>
#include <time.h>
#include <signal.h>
#include <stdlib.h>
#include <stdio.h>
static void handle_signal(int sig) {
puts("\e[0m");
exit(sig == SIGINT ? 0 : sig + 128);
}
int main() {
struct sigaction act = { .sa_handler = handle_signal };
if(sigaction(SIGINT, &act, NULL) < 0) {
perror("sigaction");
return 1;
}
struct timeval t;
int color_status = 0;
while(gettimeofday(&t, NULL) == 0) {
const char *color_code;
if(color_status) {
color_code = "\e[1;30m\e[1;47m";
color_status = 0;
} else {
color_code = "\e[0m";
color_status = 1;
}
struct tm *tm = localtime(&t.tv_sec);
fprintf(stdout, "\r%s%5d-%02d-%02d %02d:%02d:%02d",
color_code,
1900 + tm->tm_year, 1 + tm->tm_mon, tm->tm_mday,
tm->tm_hour, tm->tm_min, tm->tm_sec);
fflush(stdout);
struct timeval wait = { .tv_usec = 1000000 - t.tv_usec };
select(1, NULL, NULL, NULL, &wait);
}
perror(NULL);
return 1;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment