[英]Destructor calling when program is interrupted
我正在使用我创建的类Socket
在我的程序中创建一个套接字连接。 该程序在无限循环中运行并退出它我使用 ctrl-c。 现在当我关闭程序时,我的析构函数没有被调用(内存被释放,因为我在这里读过,但在中断程序时没有释放套接字)。 有没有办法调用析构函数退出这样的程序?
套接字类定义:
class Socket
{
private:
int m_sock;
sockaddr_in m_addr;
public:
Socket();
virtual ~Socket();
// Server initialization
bool create();
bool bind ( const int port );
bool listen() const;
bool accept ( Socket& ) const;
// Client initialization
bool connect ( const std::string host, const int port );
// Data Transimission
bool send ( const std::string ) const;
int recv ( std::string& ) const;
void set_non_blocking ( const bool );
bool is_valid() const { return m_sock != -1; }
};
析构函数定义:
Socket::~Socket(){
close(m_sock);
}
主要功能:
try {
// Create the socket
ServerSocket server ( 15000 );
std::cout << "Server running on 0.0.0.0:15000" << std::endl;
std::string res;
while(true) {
ServerSocket new_sock;
server.accept ( new_sock );
try {
while(true) {
std::string data;
new_sock >> data;
res = process_query(data, kv_map, zset_map);
new_sock << res;
}
}
catch(SocketException&) {}
}
}
catch ( SocketException& e ){
std::cout << "Exception was caught:" << e.description() << "\nExiting.\n";
}
return 0;
是的,您可以为 SIGINT 设置信号处理程序(单击 CTRL-C 时生成的信号)。 使用 C++ 标准库,您可以编写:
void close_connection(int signal)
{
delete socket; // invoke destructor
socket.close(); // Alternative, you can add a close method to your socket class
}
// Install a signal handler
std::signal(SIGINT, close_connection);
你可以在这里找到更多关于如何在 C++ 中管理信号的信息http://en.cppreference.com/w/cpp/utility/program/signal
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.