Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/164.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ C++;Windows:处理程序中的应用程序外部崩溃_C++_C++11_Visual C++_C++14 - Fatal编程技术网

C++ C++;Windows:处理程序中的应用程序外部崩溃

C++ C++;Windows:处理程序中的应用程序外部崩溃,c++,c++11,visual-c++,c++14,C++,C++11,Visual C++,C++14,我有以下功能来执行外部程序: std::string exec(const char* cmd) { char buffer[128]; std::string result = ""; FILE* pipe = _popen(cmd, "r"); if (!pipe) throw std::runtime_error("_popen() failed!"); try { while (!feof(pipe)) {

我有以下功能来执行外部程序:

std::string exec(const char* cmd) {
    char buffer[128];
    std::string result = "";
    FILE* pipe = _popen(cmd, "r");
    if (!pipe) throw std::runtime_error("_popen() failed!");
    try {
        while (!feof(pipe)) {
            if (fgets(buffer, 128, pipe) != NULL)
                result += buffer;
        }
    } catch (...) {
        _pclose(pipe);
        throw;
    }
    _pclose(pipe);
    return result;
}
是否可以以这种方式将崩溃作为异常处理(我使用dir作为示例,它不会崩溃)

std::ostringstream ossCmd;
ossCmd这不是一个“例外”;是撞车

你抓不到撞车


继续的方法是在调试器下运行程序。它将为您提供查找、诊断和纠正问题所需的信息。

< P>由于您使用Visual C++在Windows下,您可以使用该程序运行外部程序,并获得程序的退出状态。 您无法捕获其他进程内发生的任何异常,但可以检查
GetExitCodeProcess
的结果以获取异常值。从:

  • ExitProcess或TerminateProcess函数中指定的退出值
  • 进程的main或WinMain函数的返回值
  • 导致进程终止的未处理异常的异常值

当然,这假设您没有访问外部程序源的权限。如果你有外部程序的源码,那么你应该调试并修复它的问题,而不是试图从外部捕捉它。

因为“停止工作”不是C++异常,而是致命错误(不,你不能阻止它)或者微软特定的“结构化异常”。这两种方法都不能简单地捕捉到,也不能安全地继续。您能否澄清是外部程序崩溃,还是您的应用程序崩溃?这将极大地改变您的问题。@MaxVollmer:
dir
不会崩溃。由于调用的“程序”是一个简单的
dir
,我将此问题解释为“主机”程序正在崩溃。@LightnessRacesinOrbit然后应编辑/重新表述此问题。现在,在外部程序中搜索捕获异常/崩溃解决方案的人将在这里结束。请随意这样做!
std::ostringstream ossCmd;
ossCmd << "dir";
std::string cmd = ossCmd.str();

try
{
   std::string str = exec(cmd.c_str());
}
catch(...)
{

}