微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

运行无效命令时正常退出c ++

如何解决运行无效命令时正常退出c ++

我正在使用boost从我的应用程序运行命令行命令。我正在使用封装在帮助函数中的以下代码

tuple<string,int> Utility::runcommand(const string& arguments) const
{
    string response;
    int exitCode;
    try
    {
        ipstream iStream;
        auto childProcess = child(arguments,std_out > iStream);
        string line;

        while (getline(iStream,line) && !line.empty())
        {
            response += line;
        }

        childProcess.wait();
        exitCode = childProcess.exit_code();
    }
    catch (...)
    {
        // log error
        throw;
    }

    return make_tuple(response,exitCode);
}

现在,我有一个仅在具有某些属性的计算机上运行的命令。此方法返回这些机器上的预期响应和错误代码。在其他计算机上,它会引发异常。

我尝试在应该失败的机器上手动运行命令,并返回以下输出

POWERSHELL
PS C:\Users\xyz> dummy-cmd
dummy-cmd : The term 'dummy-cmd' is not recognized as the name of a cmdlet,function,script file,or operable program. Check the spelling of the name,or if a path was included,verify that the path is correct and try again.
At line:1 char:1
+ dummy-cmd
+ ~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (dummy-cmd:String) [],CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

COMMAND PROMPT
C:\Users\xyz>dummy-cmd
'dummy-cmd' is not recognized as an internal or external command,operable program or batch file.

如何运行它以使其返回非零错误代码而不是抛出异常?

解决方法

这就是您的catch子句用于处理异常的原因。不必将它们扔掉:

tuple<string,int> Utility::RunCommand(const string& arguments) const
{
    string response;
    int exitCode;
    try
    {
        ipstream iStream;
        auto childProcess = child(arguments,std_out > iStream);
        string line;

        while (getline(iStream,line) && !line.empty())
        {
            response += line;
        }

        childProcess.wait();
        exitCode = childProcess.exit_code();
    }
    catch (PlatformNotSupportedException& e)
    {
        std::cerr << "That operation is not supported on this platform." << std::endl;
        exit(1);
    }
    catch (...)
    {
        std::cerr << "Unspecified error occurred." << std::endl;
        exit(1); // give nonzero exit code
        //throw; // take out this
    }

    return make_tuple(response,exitCode);
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?