Skip to content

Instantly share code, notes, and snippets.

@axel-angel
Created September 6, 2016 07:11
Show Gist options
  • Save axel-angel/c0f111a7f71251f683cc7db83c59260c to your computer and use it in GitHub Desktop.
Save axel-angel/c0f111a7f71251f683cc7db83c59260c to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <time.h>
typedef unsigned char byte_t;
double timestamp_now() {
struct timespec t_time;
double m_time;
if (clock_gettime(CLOCK_MONOTONIC, &t_time) < 0)
return 0.0;
m_time = (double)t_time.tv_sec + ((double)t_time.tv_nsec / 1000000000.0);
return m_time;
}
int main(int argc, char**argv) {
char buffer[256];
double cTime = 0.0, lTime = 0.0;
int limit=1; // defaults to 1 sec
byte_t raw_mode = 0;
unsigned int read;
if (argc>1) { // Argument 1 is interperted as Hz or B/s with -r
limit=atoi(argv[1]);
}
if (argc>2) { // Argument 2 is binary mode
if (strcmp(argv[2], "-b") == 0) {
raw_mode = 1;
}
}
setvbuf(stdout,NULL,_IONBF,0);
if (!raw_mode) {
while ((fgets(buffer, sizeof(buffer), stdin)) != NULL) {
cTime = timestamp_now();
if (cTime - lTime >= (1.0 / limit)) {
fputs(buffer, stdout);
lTime = cTime;
}
}
}
else {
while ((read = fread(buffer, limit, 1, stdin)) > 0) {
fwrite(buffer, limit, 1, stdout);
sleep(1);
}
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment