Skip to content

Instantly share code, notes, and snippets.

@thekvs
Created January 8, 2017 18:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thekvs/639e5e9a2e7fd31b8aff396df50e2e28 to your computer and use it in GitHub Desktop.
Save thekvs/639e5e9a2e7fd31b8aff396df50e2e28 to your computer and use it in GitHub Desktop.
// g++ -Wall -Wextra -std=c++11 fakeprg.cpp -o /tmp/fakeprg
#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
#include <ctime>
#include <climits>
#include <unistd.h>
#include <signal.h>
static volatile sig_atomic_t got_sigint;
static volatile sig_atomic_t got_sigterm;
void
signal_handler(int signum)
{
if (signum == SIGINT) {
got_sigint = 1;
} else if (signum == SIGTERM) {
got_sigterm = 1;
}
}
int
main(int argc, char **argv)
{
if (argc < 3) {
std::cout << "Usage: " << argv[0] << " dir iterations" << std::endl;
return 0;
}
signal(SIGINT, signal_handler);
signal(SIGTERM, signal_handler);
int iteration = 0;
auto dir = std::string(argv[1]);
auto iterations = std::atoi(argv[2]);
time_t t;
struct tm tp;
char buff[512];
char current_file[PATH_MAX];
bool active = true;
while (active) {
snprintf(current_file, sizeof(current_file) - 1, "%s/out.%i", dir.c_str(), iteration);
std::fstream s(current_file, std::ios::out);
for (decltype(iterations) i = 0; i < iterations; i++) {
t = time(NULL);
localtime_r(&t, &tp);
strftime(buff, sizeof(buff) - 1, "%Y-%m-%d %H:%M:%S", &tp);
s << buff << std::endl;
if (got_sigint or got_sigterm) {
sleep(1);
if (got_sigint) {
s << "Got SIGINT. Exiting." << std::endl;
std::cerr << "Got SIGINT. Exiting." << std::endl;
} else if (got_sigterm) {
s << "Got SIGTERM. Exiting." << std::endl;
std::cerr << "Got SIGTERM. Exiting." << std::endl;
}
active = false;
break;
}
usleep(1e4);
}
s.close();
iteration++;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment