我有一個內核模塊我建立在一些結構一個小問題,所以我認爲這將是很好,如果有打印出結構和值的簡單方法 - 以下是小用戶態例如什麼我的意思是。Linux C:輕鬆&'漂亮'轉儲/結構的打印輸出(如在gdb中) - 從源代碼?
假設我們有如下的簡單的C示例(在bash命令的形式給出):
FN=mtest
cat > $FN.c <<EOF
#include <stdio.h> //printf
#include <stdlib.h> //calloc
struct person
{
int age;
int height;
};
static struct person *johndoe;
main()
{
johndoe = (struct person *)calloc(1, sizeof(struct person));
johndoe->age = 6;
asm("int3"); //breakpoint for gdb
printf("Hello World - age: %d\n", johndoe->age);
free(johndoe);
}
EOF
gcc -g -O0 $FN.c -o $FN
# just a run command for gdb
cat > ./gdbcmds <<EOF
run
EOF
gdb --command=./gdbcmds ./$FN
如果運行該示例中,程序將編譯和gdb將運行它,並在斷點處自動停止。在這裏,我們可以做到以下幾點:
Program received signal SIGTRAP, Trace/breakpoint trap.
main() at mtest.c:20
20 printf("Hello World - age: %d\n", johndoe->age);
(gdb) p johndoe
$1 = (struct person *) 0x804b008
(gdb) p (struct person)*0x804b008
$2 = {age = 6, height = 0}
(gdb) c
Continuing.
Hello World - age: 6
Program exited with code 0300.
(gdb) q
如圖所示,在gdb我們可以打印輸出(轉儲?)的結構指針johndoe
的價值{age = 6, height = 0}
...我想這樣做,但直接來自C程序;也就是說,作爲在下面的示例:
#include <stdio.h> //printf
#include <stdlib.h> //calloc
#include <whatever.h> //for imaginary printout_struct
struct person
{
int age;
int height;
};
static struct person *johndoe;
static char report[255];
main()
{
johndoe = (struct person *)calloc(1, sizeof(struct person));
johndoe->age = 6;
printout_struct(johndoe, report); //imaginary command
printf("Hello World - age: %d\nreport: %s", johndoe->age, report);
free(johndoe);
}
,這將導致與像輸出:
Hello World - age: 6
$2 = {age = 6, height = 0}
所以我的問題是 - 不會像想象中的函數printout_struct
是否存在 - 還是有另一種方法來打印這樣的可能嗎?
在此先感謝您的幫助,
乾杯!
不要道歉回答你自己的問題,這是在這裏鼓勵。 – dmckee 2010-07-22 20:07:36
SO的自我回答很好;在這種情況下,我會說如果您嘗試更新此答案,以便讓我們知道即使在內核模塊中該解決方案是否正常也會更好。 – ShinTakezou 2010-07-22 20:12:29
好吧 - 謝謝你;我剛剛注意到「你確定要回答你自己的問題」部分,當我試圖發佈它:)此外,添加了一個爲什麼我認爲內核模塊將無法工作的編輯.. – sdaau 2010-07-24 07:43:59