【问题标题】:How to read the failure log message displayed when a system call failed in C++?如何阅读 C++ 中系统调用失败时显示的失败日志消息?
【发布时间】:2012-02-19 01:18:18
【问题描述】:

我有一个调用测试的 C++ 代码。我正在做一个系统调用来执行这个测试。当此测试失败时,将显示类似“错误:无法发现以下组件类型的一个或多个设备:”

我有一个在 Linux redhat 上运行的 C++ 代码,它能够检测系统调用是通过还是失败。但它无法捕获错误消息(错误:无法发现以下组件类型的一个或多个设备:)并附加到日志文件或打印它。

谁能告诉我如何捕获错误消息(错误:无法发现以下组件类型的一个或多个设备:)? PS:我是实习生,任何帮助都会非常好。

#include<iostream.h>
int main () 
{   
  int i;   
  if (system(NULL)) 
    puts ("Ok");   
  else 
    exit (1);

  i=system("hpsp --discover -verbose --user Admin --oapasswd password");  

  printf ("The value returned was: %d.\n",i);

  return false;
}

【问题讨论】:

    标签: c++ linux


    【解决方案1】:

    不要使用system(),而是使用popen()。这将打开一个捕获测试程序标准输出的管道,以便您的程序可以通过管道读取它。

    示例已编辑

    #define _BSD_SOURCE 1
    #define BUFFSIZE 400
    
    #include <stdio.h>
    #include <string.h>
    
    int main(int argc, char *argv[])
    {
        char *cmd = "hpsp --discover -verbose --user Admin --oapasswd password";
    
        char  buf[BUFFSIZE];
        char* searchResult;
         int  testPassed = 0;
    
        FILE *ptr;
    
        if ((ptr = popen(cmd, "r")) != NULL)
            while (fgets(buf, BUFFSIZE, ptr) != NULL)
            {
                if ((searchResult = strstr(buf, "The test passed")) != NULL )
                {
                    testPassed = 1;
                    break;
                }
            }
    
        if (testPassed)
            printf("yea!!\n");
        else
            printf("boo!!\n");
    
        pclose(ptr);
    
        return 0;
    }
    

    【讨论】:

    • 这只会捕获命令的标准输出,而不是标准错误。如果你想要 stderr,你可以使用 shell 重定向,例如 2&gt;&amp;1,因为 popen 使用 shell 来运行命令。
    • 我不仅需要捕获标准输出,还需要知道我的系统命令是通过还是失败。我确实喜欢使用 popen(),但我不确定如何确定我的系统命令是通过还是失败。你能告诉我怎么做吗?
    • @usustarr - 需要明确的是,没有必要运行 system() 因为您使用的是 popen() 。我不知道您将要搜索的“已通过”结果字符串的具体细节,但我编辑了答案中的代码以说明如何完成。
    • @usustarr,不客气。祝你实习顺利。
    【解决方案2】:

    您可以使用dupdup2 来备份/存储stderr 文件描述符以重定向到您的日志文件。好吧,我猜无论如何错误都会出现在 stderr 上。

    如果您只想写入日志文件,这是一个示例。

    //open log file, choose whatever flags you need
    int logfd = open("whateveryourlogfileis", O_APPEND);
    
    //back up stderr file descriptor
    int stderr_copy = dup(STDERR_FILENO);
    
    //redirect stderr to your opened log file
    dup2(logfd, STDERR_FILENO);
    
    //close the original file descriptor for the log file
    close(logfd);
    
    //system call here
    
    //restore stderr
    dup2(stderr_copy, STDERR_FILENO);
    
    //close stderr copy
    close(stderr_copy);
    

    注意:dup2dup2 之前关闭目标文件描述符。 dup 只是复制文件描述符并将新的文件描述符返回给您。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-01-27
      • 1970-01-01
      • 2015-02-21
      相关资源
      最近更新 更多