我有一个内核模块我建立在一些结构一个小问题,所以我认为这将是很好,如果有打印出结构和值的简单方法 - 以下是小用户态例如什么我的意思是。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