arunmoezhi
arunmoezhi

Reputation: 3200

redirect output to a file from gdb

I'm currently printing the contents of a variable from gdb like this:

(gdb) call printf("%s",buffer)

The buffer contains a large string and I want to redirect it to a file rather than screen. Enabling logging feature in gdb will not help here. And I'm not able to use > command to redirect either. Ofcourse I can create a file in the program and write the buffer to this file and invoke the write to file through gdb. But is there a easier way out?

Upvotes: 1

Views: 2934

Answers (2)

Mark Plotnick
Mark Plotnick

Reputation: 10261

This will redirect the target's stdout to a file of your choice, call printf, then restore stdout to its previous setting. fflush is called right before changing the file descriptor, so that output gets sent to the correct place.

$ gdb f
...
(gdb) list
1   #include <stdlib.h>
2   #include <stdio.h>
3   #include <string.h>
4   
5   main()
6   {
7       char buf[] = "test";
8   
9       printf("%p  ", (void *)buf);
10      printf("%d\n", strlen(buf));
11  }
(gdb) break 10
Breakpoint 1 at 0x80484d3: file f.c, line 10.
(gdb) run
Starting program: f 
Breakpoint 1, main () at f.c:10
10      printf("%d\n", strlen(buf));
(gdb) call fflush(stdout)
0xbffff117  $1 = 0
(gdb) call dup(1)
$2 = 3
(gdb) call creat("/tmp/outputfile",0644)
$3 = 4
(gdb) call dup2(4,1)
$4 = 1
(gdb) call printf("%s\n", buf)
$5 = 5
(gdb) call fflush(stdout)
$6 = 0
(gdb) call dup2(3,1)
$7 = 1
(gdb) call close(3)
$8 = 0
(gdb) call close(4)
$9 = 0
(gdb) cont
Continuing.
4
[Inferior 1 (process 3214) exited with code 02]
(gdb) shell cat /tmp/outputfile
test

Upvotes: 2

aglasser
aglasser

Reputation: 3069

You aren't able to use > or you did not know how to use it in gdb? You can redirect output from inside of gdb. Try:

(gdb) run > out.txt

(gdb) run > /dev/null

Upvotes: 2

Related Questions