MST
星途 面试题库

面试题:C++执行带参数的复杂系统命令及错误处理

假设你要在C++程序里执行一个类似`ffmpeg -i input.mp4 -c:v libx264 -preset medium -crf 23 output.mp4`这样的复杂多媒体转码命令,需要处理命令执行失败的情况,详细说明如何设计代码结构,包括如何捕获错误信息并根据不同错误类型进行针对性处理,同时要求代码具有一定的可扩展性,方便以后修改或添加更多命令。
14.7万 热度难度
编程语言C++

知识考点

AI 面试

面试题答案

一键面试

在C++中执行外部命令并处理错误,可以使用std::systempopen等函数。这里我们使用popen函数,因为它允许我们读取命令的标准输出和标准错误,以便捕获错误信息。以下是代码结构设计的详细说明:

  1. 包含必要的头文件
#include <iostream>
#include <cstdio>
#include <cstdlib>
#include <string>
  1. 定义执行命令的函数
std::string executeCommand(const std::string& command) {
    FILE* pipe = popen(command.c_str(), "r");
    if (!pipe) {
        throw std::runtime_error("popen() failed!");
    }
    char buffer[128];
    std::string result = "";
    while (!feof(pipe)) {
        if (fgets(buffer, 128, pipe) != nullptr)
            result += buffer;
    }
    int returnCode = pclose(pipe);
    if (returnCode != 0) {
        // 根据不同的返回码进行针对性处理
        if (WIFEXITED(returnCode)) {
            int status = WEXITSTATUS(returnCode);
            if (status == 1) {
                // 例如,返回码1可能表示输入文件不存在
                std::cerr << "输入文件不存在" << std::endl;
            } else if (status == 2) {
                // 返回码2可能表示输出文件无法创建
                std::cerr << "输出文件无法创建" << std::endl;
            } else {
                std::cerr << "命令执行失败,返回码: " << status << std::endl;
            }
        } else if (WIFSIGNALED(returnCode)) {
            int signal = WTERMSIG(returnCode);
            std::cerr << "命令被信号终止,信号: " << signal << std::endl;
        }
        throw std::runtime_error("命令执行失败");
    }
    return result;
}
  1. 主函数中调用执行命令的函数
int main() {
    try {
        std::string command = "ffmpeg -i input.mp4 -c:v libx264 -preset medium -crf 23 output.mp4";
        std::string output = executeCommand(command);
        std::cout << "命令输出: " << output << std::endl;
    } catch (const std::exception& e) {
        std::cerr << "错误: " << e.what() << std::endl;
    }
    return 0;
}

代码说明

  1. executeCommand函数

    • 使用popen打开一个管道来执行命令,并将命令的输出读取到result字符串中。
    • 使用pclose关闭管道,并获取命令的返回码。
    • 根据返回码判断命令是否执行成功,如果失败,根据不同的返回码进行针对性处理,例如判断输入文件不存在、输出文件无法创建等常见错误情况。
    • 如果命令执行失败,抛出std::runtime_error异常。
  2. main函数

    • 调用executeCommand函数执行转码命令。
    • 使用try - catch块捕获可能抛出的异常,并输出错误信息。

可扩展性

  1. 添加更多命令:可以在main函数中定义不同的命令字符串,并调用executeCommand函数执行。
  2. 错误处理扩展:在executeCommand函数中,根据不同命令可能返回的错误码,继续添加更多的针对性错误处理逻辑,提高程序的健壮性。