Follow Techotopia on Twitter

On-line Guides
All Guides
eBook Store
iOS / Android
Linux for Beginners
Office Productivity
Linux Installation
Linux Security
Linux Utilities
Linux Virtualization
Linux Kernel
System/Network Admin
Scripting Languages
Development Tools
Web Development
GUI Toolkits/Desktop
Mail Systems
Eclipse Documentation

How To Guides
General System Admin
Linux Security
Linux Filesystems
Web Servers
Graphics & Desktop
PC Hardware
Problem Solutions




9.4 Stopping a program in an infinite loop

A program which goes into an infinite loop or "hangs" can be difficult to debug. On most systems a foreground process can be stopped by hitting Control-C, which sends it an interrupt signal (SIGINT). However, this does not help in debugging the problem--the SIGINT signal terminates the process without producing a core dump. A more sophisticated approach is to attach to the running process with a debugger and inspect it interactively.

For example, here is a simple program with an infinite loop:

main (void)
  usigned int i = 0;
  while (1) { i++; };
  return 0;

In order to attach to the program and debug it, the code should be compiled with the debugging option -g:

$ gcc -Wall -g loop.c
$ ./a.out
(program hangs)

Once the executable is running we need to find its process id (PID). This can be done from another session with the command ps x:

$ ps x
... .....  .    .... 
891 pts/1  R    0:11 ./a.out

In this case the process id is 891, and we can now attach to it with gdb. The debugger should be started in the directory containing the executable and its source code:(32)

$ gdb a.out
(gdb) attach 891
Attaching to program: a.out, process 891
Reading symbols from /lib/
Loaded symbols for /lib/
Reading symbols from /lib/
Loaded symbols for /lib/
0x080483d4 in main () at loop.c:5
5         while (1) { i++; };

The output shows the line that was about to execute at the point when the debugger attached to the process. The attached program is paused but still "live"---it can be examined interactively and continued or terminated (with the kill command) if necessary:

(gdb) print i
$1 = 1213315528
(gdb) kill
Kill the program being debugged? (y or n) y

If you want to stop a process immediately and create a core dump, the shell command kill -3 pid (where pid is the process id) will send it a SIGQUIT signal. The SIGQUIT signal does trigger a core dump, unlike SIGINT. Note that if core dumps were disabled when the process was started, no core file will be produced (see section 5.1 Examining core files).

  Published under the terms of the GNU General Public License Design by Interspire