Boost.Asio segfault,不知道为什么 [英] Boost.Asio segfault, no idea why

查看:200
本文介绍了Boost.Asio segfault,不知道为什么的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是从我的Boost.Asio项目的一个SSCCE根据例子。我花了大约一个小时跟踪到这个bug的错误:

This is a SSCCE from my Boost.Asio project based on the examples. It took me about an hour to track the bug down to this:

#include <boost/bind.hpp>
#include <boost/asio.hpp>
#include <boost/shared_ptr.hpp>

class Connection  {
public:
    Connection(boost::asio::io_service& io_service) : socket(io_service) {}

private:
    boost::asio::ip::tcp::socket socket;
};

class Server {
public:
    Server() : signal_monitor(io_service) {
        signal_monitor.add(SIGINT);
        signal_monitor.add(SIGTERM);

        signal_monitor.async_wait(
            boost::bind(&Server::handle_signal_caught, this)
        );
    }

    void run() {
        // comment out the next line and there's no segfault
        connection.reset(new Connection(io_service));

        io_service.run();
    }

private:
    void handle_signal_caught() {
        io_service.stop();
    }

    boost::shared_ptr<Connection> connection;
    boost::asio::io_service io_service;
    boost::asio::signal_set signal_monitor;
};

int main(int argc, char **argv) {
    Server server;
    server.run();

    return 0;
}

当我发送一个信号(ctrl + C)程序segfaults而不是关闭下来好。我已经花了最后一个半小时来看这个,但我只是不明白为什么会有segfault,你们任何人都能发现这个问题?

When I send a signal (ctrl+C) the program segfaults instead of shutting down nicely. I've spent the last half hour looking at this, but I simply do not see why this would segfault, can any of you guys spot the issue?

推荐答案

我想我发现了这个问题。请注意服务器的成员的声明顺序:

I think I found out the issue. Note the declaration order of the members of Server:

boost::shared_ptr<Connection> connection;
boost::asio::io_service io_service;
boost::asio::signal_set signal_monitor;

销毁命令的执行顺序与声明相反。这意味着首先 signal_monitor ,然后 io_service ,最后连接被毁。但连接包含一个 boost :: asio :: ip :: tcp :: socket ,其中包含对 io_service ,它被销毁。

Destruction order is done in the opposite order of declaration. This means that first signal_monitor, then io_service and finally connection get destroyed. But connection contains a boost::asio::ip::tcp::socket containing a reference to io_service, which got destroyed.

确实,这是发生了什么事,也导致了segfault:

And indeed, this is pretty much what happening, and causes a segfault too:

int main(int argc, char **argv) {
    auto io_service = new boost::asio::io_service();
    auto socket = new boost::asio::ip::tcp::socket(*io_service);

    delete io_service;
    delete socket;

    return 0;
}

之后声明连接 io_service 解决了问题。

Declaring connection after io_service solves the issue.

Damn

这篇关于Boost.Asio segfault,不知道为什么的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆