3
如何在C++中使用GDB运行程序,以便在出现错误异常(segfaults)的情况下重新启动程序(我希望GDB自动使用“运行”命令),并且同时记录到文件中的任何错误(命令“where”)。异常(segfault)错误后是否可以在GDB中自动重启程序?
是否有可能?
如何在C++中使用GDB运行程序,以便在出现错误异常(segfaults)的情况下重新启动程序(我希望GDB自动使用“运行”命令),并且同时记录到文件中的任何错误(命令“where”)。异常(segfault)错误后是否可以在GDB中自动重启程序?
是否有可能?
让我告诉你一个例子,如果它崩溃,重新启动一个程序3次。我使用python脚本来处理SIGSEGV(https://sourceware.org/gdb/onlinedocs/gdb/Events-In-Python.html)。
首先,这是一个GDB会话的例子:
>gdb -q -x restart.py ./a.out
Reading symbols from /home/a.out...done.
process id: 1700
Program received signal SIGSEGV, Segmentation fault.
0x000000000040060e in c() at main2.cpp:9
9 *ptr = *ptr +1;
#0 0x000000000040060e in c() at main2.cpp:9
#1 0x000000000040062a in main() at main2.cpp:15
process id: 1704
Program received signal SIGSEGV, Segmentation fault.
0x000000000040060e in c() at main2.cpp:9
9 *ptr = *ptr +1;
#0 0x000000000040060e in c() at main2.cpp:9
#1 0x000000000040062a in main() at main2.cpp:15
process id: 1705
Program received signal SIGSEGV, Segmentation fault.
0x000000000040060e in c() at main2.cpp:9
9 *ptr = *ptr +1;
#0 0x000000000040060e in c() at main2.cpp:9
#1 0x000000000040062a in main() at main2.cpp:15
process id: 1706
Program received signal SIGSEGV, Segmentation fault.
0x000000000040060e in c() at main2.cpp:9
9 *ptr = *ptr +1;
#0 0x000000000040060e in c() at main2.cpp:9
#1 0x000000000040062a in main() at main2.cpp:15
(gdb)
对于每个碰撞与crash.file.PID创建一个名称的文件。这是一个文件的一个例子:
>more crash.file.1860
#0 0x000000000040060e in c() at main2.cpp:9
#1 0x000000000040062a in main() at main2.cpp:15
这是C++程序:
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
int c()
{
printf("process id: %d\n", getpid());
int *ptr =0;
*ptr = *ptr +1;
return *ptr;
}
int main()
{
c();
return 0;
}
这是一个Python脚本:
>cat restart.py
#!gdb
import sys
import gdb
import os
number_restarts = 3
def on_stop(sig):
global number_restarts
if isinstance(sig, gdb.SignalEvent) and sig.stop_signal == "SIGSEGV":
crash_file = "crash.file." + str(gdb.selected_inferior().pid)
gdb.execute("set logging file " + crash_file)
gdb.execute("set logging on")
gdb.execute("where")
gdb.execute("set logging off")
if (number_restarts > 0):
number_restarts -= 1
gdb.execute("set confirm off")
gdb.execute("kill")
gdb.execute("run")
gdb.events.stop.connect (on_stop)
gdb.execute("set pagination off")
gdb.execute("run")
如果C程序要求的命令行参数,然后它将通过restart.py文件中的gdb.execute(“run --args”)给出。 –