【问题标题】:C++: Calling sendmail from pthread results in Broken PipeC++:从 pthread 调用 sendmail 导致管道损坏
【发布时间】:2017-11-15 20:41:02
【问题描述】:

我正在尝试在单独的pthread 中发送一封带有sendmail 的电子邮件。这段代码在 99.9% 的情况下都有效。

void* emailClientThreadFct(void* emailClientPtr)
{
   EmailClient* emailClient = static_cast<EmailClient*>(emailClientPtr);

   try
   {
      emailClient->Send();
   }
   catch (const exception& excep)
   {
      SYSLOG_ERROR("E-mail client exception: %s", excep.what());
   }

   delete emailClient;
   return NULL;
}

// Send email for current output in a separate thread
pthread_t emailThread;
pthread_attr_t attr;

/* Initialize and set thread detached attribute */
pthread_attr_init(&attr);
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);

pthread_create(&emailThread, &attr, emailClientThreadFct, emailClientObj);

0.1% 的时间,我在执行以下调用时收到错误 fwrite error Broken Pipe。根据我的阅读,Broken Pipe (EPIPE 32) 通常是一个接收器问题,但 sendmail 是一个本地进程......可能是我发送了太多数据来 fwrite 吗?或者我在我的 pthread 实例化中做错了什么?还是 sendmail 崩溃了?

void EmailClient::Send() const
{
   // Flush all open output streams, as recommended by popen man page
   fflush(NULL);

   string popen_command = "sendmail -t -oi >/dev/null 2>&1");

   // Open pipe to Mail Transport Agent (MTA)
   errno = 0;
   FILE* stream = popen(popen_command.c_str(), "w");

   if (stream == NULL)
   {
      throw exception("Cannot send email popen");
   }
   errno = 0;
   if (fwrite(message.data(), message.size(), 1, stream) < 1)
   {
      pclose(stream);
      throw exception("fwrite error ", strerror(errno));
   }

   // Close MTA
   errno = 0;
   if (pclose(stream) == -1)
      printf("\"Error closing the MTA pipe (%s)\"", strerror(errno))
}

【问题讨论】:

    标签: c++ pthreads sendmail popen broken-pipe


    【解决方案1】:

    EPIPE 表示另一端(您正在写入的进程)已经死亡。如果 fork 失败(popen 调用 shell,因此涉及另一个子进程),则可能会发生这种情况,因为系统中的进程暂时过多。更直接的原因是 sendmail 在读取所有标准输入之前失败并过早退出,例如由于电子邮件标头格式错误。

    popen 不幸的是不是一个非常可靠的接口。您最好使用fork/execveposix_spawn,使用临时文件用于输入或使用poll 进行I/O 多路复用,以便能够捕获sendmail 可能生成的任何错误.或者,您可以尝试使用-oee 调用sendmail,这应该通过电子邮件报告任何错误,但如果sendmail 本身的创建失败,它将无济于事。

    【讨论】:

    • 是 sendmail 意外退出,因为我们传递了格式错误的电子邮件地址。谢谢你的提示!
    猜你喜欢
    • 1970-01-01
    • 2016-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-09-08
    • 2015-02-09
    • 2017-01-31
    相关资源
    最近更新 更多