Skip to content

Instantly share code, notes, and snippets.

@mkolod
Last active September 27, 2020 04:12
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save mkolod/33b552541ca95e6c70e8a0ff8bfd7a9f to your computer and use it in GitHub Desktop.
Save mkolod/33b552541ca95e6c70e8a0ff8bfd7a9f to your computer and use it in GitHub Desktop.
Redirect Streams and CUDA checks
#include <csignal>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <unistd.h>
#include <limits.h>
#include <iostream>
#include <sstream>
#include <stdexcept>
#include <tuple>
#include <cuda.h>
#include <cuda_runtime_api.h>
namespace {
class RedirectSingleton {
private:
static RedirectSingleton* instance;
static std::fstream* file;
RedirectSingleton() {}
public:
static RedirectSingleton* getInstance() {
if (instance == nullptr) {
instance = new RedirectSingleton;
file = new std::fstream;
for (const int sig : {SIGABRT, SIGFPE, SIGILL, SIGINT, SIGTERM, SIGSEGV}) {
signal(sig, RedirectSingleton::signalHandler);
}
char* hostname = new char[255];
gethostname(hostname, 255);
const char* path = std::getenv("KERNEL_DEBUG_PATH");
if (path != "") {
const char* log_path = const_cast<char*>((std::string(path)+ "_"+ std::string(static_cast<const char*>(hostname)) + "_" + std::to_string(getpid())).c_str());
file->open(log_path, std::ios::out);
std::streambuf* stream_buffer_cout = std::cout.rdbuf();
std::streambuf* stream_buffer_file = file->rdbuf();
std::cout.rdbuf(stream_buffer_file);
std::cerr.rdbuf(stream_buffer_file);
std::cout << "Test" << std::endl;
}
}
return instance;
}
static void signalHandler(int signum) {
if (file->is_open()) {
file->close();
}
exit(signum);
}
};
RedirectSingleton* instance = RedirectSingleton::getInstance();
RedirectSingleton* RedirectSingleton::instance = instance->instance;
std::fstream* RedirectSingleton::file = instance->file;
} // namespace
inline void gpuAssert(cudaError_t code, const char *file, int line)
{
if (code != cudaSuccess)
{
std::stringstream ss;
ss << "GPU error: " << cudaGetErrorString(code) << ", in file " << file << ", line: " << line;
std::cout << ss.str() << std::endl;
throw std::runtime_error(ss.str());
}
}
#define gpuErrchk(ans) \
{ \
gpuAssert((ans), __FILE__, __LINE__); \
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment