user1762571
user1762571

Reputation: 1949

How to generate a core dump without crashing down a process in c?

Is it possible to generate a mini core dump for debugging purpose without crashing the process. Let's say if a function receives an unexpected value, just printing logs and returning gracefully might not be sufficient to debug the issue. On the other hand, if i can get a screenshot of memory and look at the stack, i could find more useful information to debug.

Upvotes: 1

Views: 3940

Answers (2)

Stargateur
Stargateur

Reputation: 26697

There is not building function to do that, you could use ptrace() to debug your own process but it would not be easy. Call gcore is the easiest method.

#include <stdio.h>
#include <unistd.h>
#include <inttypes.h>
#include <sys/wait.h>

int main(void) {
  pid_t parent = getpid();
  pid_t pid = fork();
  if (pid < 0) {
    // oh dear we are on trouble
  } else if (pid == 0) {
    char tmp[42];
    snprintf(tmp, sizeof tmp, "%" PRIdMAX, (intmax_t)parent);
    execvp("gcore", (char *[]){"gcore", tmp, NULL});
  } else {
    int wstatus;
    waitpid(pid, &wstatus, 0);
  }
}

Upvotes: 1

user9232447
user9232447

Reputation:

Yes,

According to gdb's documentation, once attached with gdb you may issue the following command:

(gdb) gcore
(gdb) q

This will dump the core to "core.pid" without crashing the process.

or this one-liner:

sudo sh -c 'echo gcore <output_core> | gdb -p <pid>'

Upvotes: 3

Related Questions