int main(int argc, char** argv) { std::string logs_path = "/home/sage/logs/"; std::string folder1_name = logs_path + get_current_time_M_10(); create_folder(folder1_name); ros::init(argc, argv, "log_fetch"); ros::NodeHandle nh; ros::Subscriber sub = nh.subscribe("/rosout", 1000, callback); //ros::Timer timer1 = nh.createTimer(ros::Duration(600), new_folder_callback); //std::this_thread::sleep_for(std::chrono::seconds(1)); //ros::spin(); bool s=true; while(s){ auto now1 = std::chrono::system_clock::now(); std::time_t now_c1 = std::chrono::system_clock::to_time_t(now1); std::tm parts1 = *std::localtime(&now_c1); if (parts1.tm_min % 10 == 0) { std::string folder_name = logs_path + get_current_time(); create_folder(folder_name); s=false; } } ros::Timer timer1 = nh.createTimer(ros::Duration(600), new_folder_callback); ros::spin(); return 0; }如何修改代码能使程序不发生阻塞
时间: 2024-03-28 19:42:17 浏览: 17
可以将程序中的循环改为使用定时器来触发创建文件夹的操作,这样就不会发生阻塞。具体做法是:注释掉 while 循环部分,取消注释定时器相关的代码,并修改定时器回调函数 new_folder_callback(),使其创建文件夹的操作与原来的 while 循环中的代码一致。修改后的代码如下:
```c++
int main(int argc, char** argv) {
std::string logs_path = "/home/sage/logs/";
std::string folder1_name = logs_path + get_current_time_M_10();
create_folder(folder1_name);
ros::init(argc, argv, "log_fetch");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("/rosout", 1000, callback);
ros::Timer timer1 = nh.createTimer(ros::Duration(600), new_folder_callback);
ros::spin();
return 0;
}
void new_folder_callback(const ros::TimerEvent&){
std::string folder_name = logs_path + get_current_time();
create_folder(folder_name);
}
```
其中,new_folder_callback() 函数是定时器回调函数,在代码中使用 ros::Timer 创建了一个定时器,每隔 600 秒就会触发一次 new_folder_callback() 函数。这样,定时器将会代替原来的 while 循环,不会发生阻塞。