2013-10-07 25 views
0

我在Linux系統上Linux:對於Sendmail的錯誤代碼未找到

int sendEMail (string sEMailAddress, string sEMailSubject , string sEMailText) 
{ 

int nRc = nOK; 
    // send email here 
    const int nBUFFERSIZE = 55000; 
    static char szCommand [ nBUFFERSIZE ] = { 0 }; 
    const char * szEmailText = NULL; 


    FILE *fpipe = popen("sendmail -t", "w"); 

    szEmailText=sEMailText.c_str(); 

    if (fpipe != NULL) 
    { 
     fprintf(fpipe, "To: %s\n", sEMailAddress.c_str()); 
     fprintf(fpipe, "From: %s\n", "[email protected]"); 
     fprintf(fpipe, "Subject: %s\n\n", sEMailSubject.c_str()); 
     fwrite(sEMailText.c_str(), 1, strlen(sEMailText.c_str()), fpipe); 
     pclose(fpipe); 
    } 
    else 
    { 
     Logger_log (1 , "ERROR: Cannot create pipe to mailx"); 
       nRc = -1; 

    } 
    return nRc; 
} 

此代碼工作正常展開下面的C++代碼。我必須確保在System上找到sendmail。因爲我有一個問題。 PATH變量設置不正確。因此在System上找不到sendmail。沒有錯誤消息,我收到。電子郵件似乎發出。但事實並非如此。如何在代碼(返回或錯誤代碼)中實現,如果Sendmail進程無法找到,我收到錯誤消息? thanx提前

回答

0

的一種方式(具體檢查命令未找到錯誤)

2(stderr)是linux系統默認的文件描述符。

將此錯誤重定向到文件錯誤文件。現在比較錯誤文件的內容,並且如果內容具有command not found字符串,則可以確保找不到命令。

FILE* fpipe = popen("sendmail 2>errorfile", "w"); 

FILE* file = fopen("complete path to errorfile", "r"); 

char buf[124]; 

fgets(buf, 100, file); 

printf("%s", buf); 

if(strstr(buf, "command not found")!=NULL) 
    printf("Command not found"); 

其他方式

system功能可用於

#include <stdlib.h> 

int i; 
i = system("sendmail"); 
printf("The return value is %d", i); 

該返回值可以用來檢查命令是否成功執行。返回值是你的機器操作系統的依賴,所以檢查返回值是什麼。然而,成功通常爲零。

0

我不知道,但我認爲從手動有一些答案:
1. POPEN調用/ bin/sh的-c <您的命令>,所以我想POPEN永遠成功,除非/ bin/sh的是沒有找到
2.你應該檢查返回代碼:

int ret_code=pclose(fpipe); 
if (ret_code != 0) 
{ 
    // Error handling comes here 
} 

從使用手冊(man POPEN)

的函數,pclose()函數等待相關的進程終止和重新打開wait4(2)返回的命令的退出狀態。

...

的函數,pclose()函數返回-1,如果wait4(2)返回一個錯誤,或當檢測到某些其他錯誤。

+0

thanx。它似乎工作 – beterman

+0

偉大的。很高興聽到。你能接受答案嗎? – shayst