2

Asio has code to ignore SIGPIPE which is in Signal_init.hpp, however there is a macro warp it in io_service.hpp:

#elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \
  || defined(__osf__)

I compile in Ubuntu found the macro doesn't enabled, so std::signal(Signal, SIG_IGN); haven't been called.

However, when I write to an closed socket by asio, it can report EPIPE error by boost::system::error_code which in complete handler. According to libc doc:

In this case, send generates a SIGPIPE signal first; if that signal is ignored or blocked, or if its handler returns, then send fails with EPIPE.

How asio set with SIGPIPE let process to ignore it? Does asio do some special on this?

Community
  • 1
  • 1
jean
  • 2,825
  • 2
  • 35
  • 72

1 Answers1

0

You can simply tell the OS you want SIGPIPE ignored.

Asio has the code to do that here http://www.boost.org/doc/libs/1_65_1/boost/asio/detail/signal_init.hpp

Strangely (?) it is only included on old-fashioned UNIX:

#if defined(BOOST_ASIO_WINDOWS) || defined(__CYGWIN__)
# include <boost/asio/detail/winsock_init.hpp>
#elif defined(__sun) || defined(__QNX__) || defined(__hpux) || defined(_AIX) \
  || defined(__osf__)
# include <boost/asio/detail/signal_init.hpp>
#endif

You can simply do this yourself:

#include <csignal>

// ...
std::signal(SIGPIPE, SIG_IGN);

Or you can use the Asio signal-set class:

#include <boost/asio.hpp>
#include <boost/asio/signal_set.hpp>
#include <iostream>

boost::asio::io_service svc;
boost::asio::signal_set ss(svc);

static void ignore_signal(boost::system::error_code ec, int /*signal*/) {
    if (!ec) ss.async_wait(ignore_signal);
    // std::cout << "\n" << ec.message() << "\n";
}

int main() {
    ss.add(SIGPIPE);
    ss.add(SIGINT);
    ss.async_wait(ignore_signal);
    svc.run();
}
Gyorgy Szekely
  • 2,654
  • 3
  • 23
  • 32
sehe
  • 374,641
  • 47
  • 450
  • 633
  • I'm curious how asio deal with that. It doesn't ignore SIGPIPE, haven't use MSG_NOSIGNAL. But when I continue write to an disconnected socket, there is no SIGPIPE at all! – jean Sep 08 '17 at 01:31