gpt4 book ai didi

c++ - 在 libpthread 链接的应用程序中捕获异常时出现段错误(linux、C++)

转载 作者:太空狗 更新时间:2023-10-29 12:08:16 26 4
gpt4 key购买 nike

我这里有这段代码:

这些是用于创建和停止 pthread 的函数:

void WatchdogController::conscious_process_handler_start() {

if ( debug ) cout << "WatchdogController: starting conscious process thread" << endl;

cn_pr_thread_active = true;

if ( pthread_create( &cn_pr_thread, NULL, conscious_process_handler, this ) < 0 ) {
cn_pr_thread_active = false;
throw WatchdogException( "Unable to start new thread" );
}
}

void WatchdogController::conscious_process_handler_stop() {

if ( debug ) cout << "WatchdogController: stopping conscious process thread" << endl;

cn_pr_thread_active = false;

int *retval;

pthread_join( cn_pr_thread, ( void ** )&retval );

if ( *retval < 0 ) {
delete retval;
string err = string( "Error returned by conscious_process_handler(): " ) + string( pthread_err );
throw WatchdogException( err.c_str() );
}

delete retval;
}

我在传递给 pthread 的函数中使用 select(),当它停止时返回一个错误,导致 pthread 的返回值为负,但这不是问题,我稍后会修复它 - 问题是,当异常被扔在这里:

throw WatchdogException( err.c_str() );

并在这里捕获:

try {
watchdog_controller->hardware_watchdog_stop();
watchdog_controller->unconscious_process_handler_stop();
watchdog_controller->conscious_process_handler_stop();
}
catch ( HardwareWatchdogException &e ) {
cerr << "Error stopping hardware watchdog!" << endl;
cerr << e.get_reason() << endl;
string err = string( "Exception thrown by hardware watchdog controller" ) + string( e.get_reason() );
if ( log ) write_log( err.c_str() );
delete watchdog_controller;
return -1;
}
catch ( WatchdogException &e ) {
cerr << "Exception cought when exiting!" << endl;
cerr << e.get_reason() << endl;
string err = string( "Exception cought when exiting" ) + string( e.get_reason() );
if ( log ) write_log( err.c_str() );
delete watchdog_controller;
return -1;
}

此时我尝试访问对象时出现段错误:

cerr << e.get_reason() << endl;

可能是什么原因?

Reference &e 指向某物,但地址似乎无效。

这是异常类:

class WatchdogException {

public:

/**
@brief Default constructor
*/
WatchdogException() : reason() {
}

/**
@brief Overloaded constructor - setting the error message
@param why Error message
*/
WatchdogException( const char *why ) : reason( why ) {
}

/**
@brief The destructor
*/
virtual ~WatchdogException() {
}

/**
@brief A getter for the error message
@return Returns a string containing error description
*/
virtual std::string get_reason() const {
return reason;
}

protected:

/**
@var reason String containing the error message
*/
std::string reason;

};

最佳答案

我猜测您没有为 retval 正确分配内存,或者您以某种方式从 cn_pr_thread 返回了一个无效指针,这就是为什么在调用 时出现段错误的原因pthread_join

关于c++ - 在 libpthread 链接的应用程序中捕获异常时出现段错误(linux、C++),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1648424/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com