### 10.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:

    int
    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
    PID TTY    STAT TIME COMMAND
    ... .....  .    ....
    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:38

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

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
    (gdb)

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 Examining core files).

#### Footnotes

##### (38)

Alternatively, the appropriate paths can be set up in `gdb` using the `file` and `directory` commands.