1

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.

user1762571
  • 1,888
  • 7
  • 28
  • 47

2 Answers2

2

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>'
  • 1
    Why use `sudo`? – Barmar May 01 '18 at 01:39
  • @Barmar Good point. Unless it's root process (and I would question 'why' the question is wanting this - and I'd question the validity of such a test too) or there's some limitation in place (though nothing comes to mind atm) there's no need at all to use sudo since they're no need to be root at all. It seems rather silly to be root just to kill a process that isn't owned by root - and unnecessary too. – Pryftan Oct 22 '19 at 18:12
1

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);
  }
}
Stargateur
  • 24,473
  • 8
  • 65
  • 91
  • I tried this and dont see coredump getting generated in ubuntu. am i missing something? – user1762571 May 01 '18 at 01:55
  • where can find a core file. I don't see it in current directory or in this location /proc/sys/kernel/core_pattern – user1762571 May 01 '18 at 14:21
  • @user1762571 This is what you mean by code dump... That wasn't clear in your question, http://man7.org/linux/man-pages/man5/core.5.html. – Stargateur May 01 '18 at 14:51
  • I want to generate it from code and don't want to use external utility like gcore – user1762571 May 01 '18 at 15:08
  • You can specify "-o" and "" in the arguments array of execvp to generate the core file at desired location and name. Gcore would also require that your program runs with root access(sudo ./your_application) – Karan Joisher Jul 05 '19 at 15:28
  • @KaranJoisher Exactly why would it require it to be root? You can generate a core without being root - it's all about permissions and the same user/etc. would work just as well. Much like if you were to send a SIGSEGV to it directly or if you dereferenced a NULL pointer or ... – Pryftan Oct 22 '19 at 18:15