【问题标题】:Linux: Error Code for Sendmail not FoundLinux:未找到 Sendmail 的错误代码
【发布时间】:2013-10-07 08:17:41
【问题描述】:

我在 Linux 系统上部署了以下 C++ 代码

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", "test@mail.de");
        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;
}

此代码运行良好。我必须确保应该在 System.sendmail 上找到 sendmail。因为我有一个问题。 PATH 变量设置不正确。因此在系统上找不到 sendmail。我没有收到错误消息。电子邮件似乎发送出去。但事实并非如此。如果找不到 Sendmail 进程,我如何在代码(返回或错误代码)中意识到我收到错误消息? 提前致谢

【问题讨论】:

    标签: c++ linux sendmail


    【解决方案1】:

    我不确定,但我认为从手册中有一些答案:
    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) 返回的命令的退出状态。

    ...

    如果 wait4(2) 返回错误或检测到其他错误,则 pclose() 函数返回 -1。

    【讨论】:

      【解决方案2】:

      一种方法(专门检查命令未找到错误)

      2(stderr)是linux系统默认的文件描述符。

      将此错误重定向到文件errorfile。现在比较 errorfile 的内容,如果内容有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);
      

      这个返回值可以用来检查命令是否执行成功。返回值取决于您的机器操作系统,因此请检查返回值是什么。但是,成功通常为零。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2016-11-12
        • 2015-07-03
        • 2015-02-20
        • 1970-01-01
        • 2015-10-28
        • 1970-01-01
        相关资源
        最近更新 更多