c++ - 在没有 coredump 或 Segmentation Faults 的情况下退出程序

标签 c++ exit terminate quit

我想知道是否有一些方法可以在不引起segfaultcore dump 的情况下突然退出/终止程序。

我查看了 terminate()exit() 以及 return 0。它们似乎都不适用于我的项目。

if(this->board.isComplete())
 {
     Utils::logStream << " complete "<< endl;
     this->board.display();
     exit(0);
     //std::terminate();
     //abort();
     //raise(SIGKILL);
     return true;
}

最佳答案

exit()/abort() 和类似函数通常不是终止 C++ 程序的正确方法。正如您所注意到的,它们不运行 C++ 析构函数,使您的文件流保持打开状态。如果你真的必须使用 exit(),然后用 atexit() 注册一个清理函数是个好主意,但是,我强烈建议您改用 C++ 异常。对于异常,会调用析构函数,如果在终止之前需要进行一些顶级清理,您始终可以在 main() 上捕获异常,进行清理,然后正常返回并返回错误代码.这也可以防止代码转储。

int main()
{
    try 
    {
        // Call methods that might fail and cannot recover.
        // Throw an exception if the error is fatal.
        do_stuff();
    }
    catch(...)
    {
        // Return some error code to indicate the 
        // program didn't terminated as it should have.
        return -1;
    }

    // And this would be a normal/successful return.
    return 0;
}

关于c++ - 在没有 coredump 或 Segmentation Faults 的情况下退出程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24987847/

相关文章:

Java - JInternalFrame - 无法从 JFrame 关闭 JInternalFrame‏

c++ - 如何自定义未捕获的异常终止行为?

Android - applicationWillTerminate 等效

c++ - 什么相当于 Linux 中的 Win32 消息泵?

c++ - 使用deque的滑动窗口(运行时错误)

c++ - 简单 C++ 程序上的过程入口点错误

c - C 中使用 char 退出

c++ - 从文本文件中提取文件名

android - 是否有适用于 Android 的 Application::onDestroy() 等效项?

c - 退出状态是可观察的行为吗?