我有一个使用工作队列执行任务的程序,并且应该作为守护进程运行。我一直在使用以下代码实现这一点:
bool seedDaemon() {
using namespace std;
int childpid = 0;
pid_t pid = 0;
if( ( childpid = fork() ) < 0 ) {
return false;
}
else if( childpid > 0 ){
exit(0);
}
setsid();
umask(0);
std::cout<< "[OK]\n";
close( fileno(stderr) );
close( fileno(stdout) );
close( STDIN_FILENO );
return true;
}
这将关闭原始进程并启动另一个进程。但是,这导致了我为执行任务而创建的线程在分叉后没有再次出现的问题。我的工作队列是全局实例化的,所有其他值和内存地址都正确复制到子节点,但线程没有。
作为参考,这里是池类:
池.h:
#ifndef __POOL_H
#define __POOL_H
class tpool {
public:
tpool( std::size_t tpool_size );
~tpool();
template< typename Task >
void run_task( Task task ){ // add item to the queue
io_service_.post( boost::bind( &tpool::wrap_task, this,
boost::function< void() > ( task ) ) );
}
private:
boost::asio::io_service io_service_;
boost::asio::io_service::work work_;
boost::thread_group threads_;
boost::mutex mutex_;
void wrap_task( boost::function< void() > task );
};
extern tpool dbpool;
#endif
池.cpp:
#include <boost/asio/io_service.hpp>
#include <boost/thread/mutex.hpp>
#include <boost/bind.hpp>
#include <boost/thread.hpp>
#include "pool.h"
tpool::tpool( std::size_t tpool_size ) : work_( io_service_ ), available_( tpool_size ) {
for ( std::size_t i = 0; i < tpool_size; ++i ){
threads_.create_thread( boost::bind( &boost::asio::io_service::run, &io_service_ ) );
}
}
tpool::~tpool() {
io_service_.stop();
try {
threads_.join_all();
}
catch( ... ) {}
}
void tpool::wrap_task( boost::function< void() > task ) {
// run the supplied task
try {
task();
} // suppress exceptions
catch( ... ) {
}
boost::unique_lock< boost::mutex > lock( mutex_ );
++available_;
}
tpool dbpool( 50 );
那么我该如何解决呢?