Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to debug a running C++ program in Linux?

Tags:

c++

debugging

gdb

I have a question about debugging a running C++ program in Linux. If a programming is already running and can't be interrupted, how to do that.

I can find three ways, but I don't know too much about details, I am grateful if any one can elaborate it deeper.

1) we can use GDB by specifying the process ID

gdb -p PID

In this case, what's the difference between this and attach PID?

2) We can use pstat, however, I am using Ubuntu, no pstat, but only mpstat

it seems that mpstat does not provide too much information, and not so many options.

3) check the details information under directory ./proc

In this case, just go to the directory with the PID. However, should this be done mannually?

like image 866
skydoor Avatar asked Mar 18 '10 03:03

skydoor


People also ask

How do I debug a file in Linux?

You can use gdb's command files to accomplish this by putting breakpoints in separate files and instructing gdb to load them. Also, instead of running gdb, you can use the script above, which let's you select which renderer process to debug. Note: you might need to use the full path to the script and avoid $HOME or ~/.


2 Answers

I can't find -p option in gdb man or their documentation, but it does work! I've tried it many times with older versions on RedHat and 7.0.1 on Debian.

I'm not sure how exactly it finds the exe by PID (maybe /proc/<PID>/exe), but it does. Since it's not described in their documentation, perhaps it not the most recommended way, but I haven't had any problems with it.

There's no noticeable difference between gdb -p <PID> and running gdb and in the their shell typing attach <PID>.

I personally prefer ps xa| grep myprogram for getting the PID

like image 76
Dmitry Yudakov Avatar answered Sep 22 '22 04:09

Dmitry Yudakov


In regards to technique 1, there is no -p flag and you still need the name of the program:

gdb prog PID

There is no difference between doing that vs running gdb prog and then telling gdb attach pid.

like image 40
R Samuel Klatchko Avatar answered Sep 22 '22 04:09

R Samuel Klatchko