Io 捕获gcc/glibc致命错误

Io 捕获gcc/glibc致命错误,io,Io,我有一个二进制文件,偶尔会抛出致命错误。我无法访问源代码,但它可能类似于以下编译为test.a的C++代码: #include <ctime> int main() { int *a = new int; delete a; time_t t=time(0); if (t%2==0) delete a; return 0; } 当我问到为什么会发生这种情况时,我得到的回答是“gcc(可能还有glibc)直接打开/dev/tty,绕过IO重定

我有一个二进制文件,偶尔会抛出致命错误。我无法访问源代码,但它可能类似于以下编译为
test.a
C++
代码:

#include <ctime>
int main() {
   int *a = new int;
   delete a;
   time_t t=time(0);
   if (t%2==0)
      delete a;
   return 0;
}
当我问到为什么会发生这种情况时,我得到的回答是“
gcc
(可能还有
glibc
)直接打开
/dev/tty
,绕过IO重定向输出这样的致命错误”

但是,如果能够从脚本中捕获此错误,那将是非常好的。由于它是随机发生的,而不是一直发生,因此重试会很有用,例如:

while :; do
    ./test.a 2>/tmp/Error
    ERROR="$(</tmp/Error)"
    if [ -z "$ERROR" ]; then
        echo "Smooth run!"
        break
    else
        echo "Error occured. Retry!"
    fi
done
因此,我想知道是否有办法捕获致命错误,然后重试运行有缺陷的二进制文件(我主要寻找linux解决方案)

编辑:

如果直接从脚本调用二进制文件,则可以通过检查退出状态来实现所需的行为:

while :; do
    ./test.a
    if (( $? == 0 )); then
        echo "Smooth run!"
        break
    else
        echo "Error occured. Retry!"
    fi
done
当然,要使其工作,可调用可执行文件本身必须正确编写。例如,在我的实际情况中,导致错误的二进制文件本身是从另一个二进制文件调用的。让我们考虑<代码> TEST2。< /代码>编译以下代码的结果:

#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
   std::system("./test.a");
   cout<<"Execution of test.a finished"<<endl;
   return 0;
}

如何避免这种情况(因为我无法修改二进制文件),我仍然不知道。

关于
gdb
-ing核心转储,你能看到至少一个堆栈跟踪吗?@peterh但是我如何从脚本中知道核心转储首先发生在agh?我不明白,请更正“agh”@peterh抱歉。但是我如何从脚本中知道核心转储首先发生在哪里呢?
while :; do
    ./test.a
    if (( $? == 0 )); then
        echo "Smooth run!"
        break
    else
        echo "Error occured. Retry!"
    fi
done
#include <cstdlib>
#include <iostream>
using namespace std;
int main() {
   std::system("./test.a");
   cout<<"Execution of test.a finished"<<endl;
   return 0;
}
*** Error in `./test.a': double free or corruption (fasttop): 0x0000000002431010 ***
Aborted (core dumped)
Execution of test.a finished
Smooth run!