Linux:找不到 Sendmail 的错误代码

Linux: Error Code for Sendmail not Found

本文关键字:错误代码 Sendmail 找不到 Linux      更新时间:2023-10-16

i 在 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: %sn", sEMailAddress.c_str());
        fprintf(fpipe, "From: %sn", "test@mail.de");
        fprintf(fpipe, "Subject: %snn", 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;
}

此代码工作正常。我必须确保应该在系统上找到发送邮件。因为我遇到了一个问题。路径变量设置不正确。因此,在系统上找不到发送邮件。我没有收到错误消息。电子邮件似乎已发送出去。但事实并非如此。如果找不到 Sendmail 进程,如何在代码(返回或错误代码)中意识到我收到错误消息?提前感谢

我不确定,但我认为从手册中有一些答案:
1. popen 调用/bin/sh -c <你的命令>所以我想 popen 总是会成功,除非找不到
/bin/sh2.您应该检查返回代码:

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

从手册页(男人打开)

pclose() 函数等待关联的进程终止,并返回 wait4(2) 返回的命令的退出状态。

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

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

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);

此返回值可用于检查命令是否成功执行。返回值取决于您的计算机操作系统,因此请检查返回值。但是,成功通常为零。