2013-10-07 62 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