2012-02-15 25 views
1

我有一個調用測試的C++代碼。我正在做一個系統調用來執行這個測試。當此測試失敗時,它將顯示如下所示「錯誤:無法發現以下組件類型的一個或多個設備:」如何在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; 
} 

回答

4

而不是使用system()使用popen()的。這將打開一個捕獲測試程序標準輸出的管道,以便您的程序可以通過管道讀取它。

EDITED

#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; 
} 
+0

這隻會捕獲stdout的命令,而不是stderr。如果你想要stderr,你可以使用shell重定向,比如'2>&1',因爲popen使用shell來運行命令。 – 2012-02-15 03:17:48

+0

我不僅需要捕獲stdout,還需要知道我的系統命令是否通過。我喜歡使用popen(),但我不知道如何弄清楚我的系統命令是否通過了。你能告訴我怎麼做嗎? – usustarr 2012-02-17 22:08:00

+0

@usustarr - 要清楚,不需要運行system(),因爲您正在使用popen()來代替。我不知道您要搜索的「已通過」結果字符串的具體情況,但我在回答中編輯了代碼,以說明如何完成此操作。 – Duck 2012-02-18 17:20:45

1

您可以使用dupdup2備份/存儲標準錯誤文件描述符重定向到您的日誌文件。好吧,我猜錯誤無論如何都會出現在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); 

注:dup2關閉dup2前,目標文件描述符荷蘭國際集團給它。 dup只是複製文件描述符,並返回給你新的文件描述符。

相關問題