#include 
#include 
#include 
#include 
#include 
#include 
#include 

#include 

void write_backtrace();

int main() {
  write_backtrace();
  return 0;
}

// Compile and link all code being traced with:  gcc -g -O0 -rdynamic
// NOTE: -g -O0 is optional, but some call frames may not present correctly
//     without this.
//     The flag -rdynamic is needed if you want to see symbol names in your
//     base executable (e.g., a.out).  Your dynamic symbols should
//     be visible even without -rdynamic.
// Use CFLAGS, CXXFLAGS and LDFLAGS if compiled automatically.
// Static function names will not be displayed.
void write_backtrace() {
  const int size=100;
  void *buffer[100];
  char file[100];
  sprintf(file, "backtrace.txt.%ld", time(NULL));
  int fd = open(file, O_WRONLY|O_CREAT|O_APPEND,
		S_IRUSR|S_IRWXG|S_IRWXO|S_IWUSR);
  sprintf(file, "\n=== Process %d, Time: %ld ===\n", getpid(), time(NULL));
  write(fd, file, strlen(file));
  int num = backtrace((void **)&buffer, size);
  backtrace_symbols_fd(buffer, num, fd);
  close(fd);
}