ros之Initialization and Shutdown

ros之Initialization and Shutdown

Initialization

方法一:

ros::init(argc, argv, "my_node_name");

方法二:

 ros::init(argc, argv, "my_node_name", ros::init_options::AnonymousName);

There are other forms of ros::init() that do not take argc/argv, instead taking explicit remapping options. Specifically, there are versions that take a std::map<std::string, std::string> and a std::vector<std::pair<std::string, std::string> >.

Initialization Options

See also: ros::init_options code API

  • ros::init_options::NoSigintHandler

Don't install a SIGINT handler. You should install your own SIGINT handler in this case, to ensure that the node gets shutdown correctly when it exits. Note that the default action for SIGINT tends to be to terminate the process, so if you want to do your own SIGTERM handling you will also have to use this option.

  • ros::init_options::AnonymousName

Anonymize the node name. Adds a random number to the end of your node's name, to make it unique.

  • ros::init_options::NoRosout

Don't broadcast rosconsole output to the /rosout topic.

start a ros node

ros::NodeHandle nh;
ros::NodeHandle priv_nh("~");

Shutting Down

在程序中使用ros::shutdown()函数可以终止程序对应的节点。 使用ctrl + c会终止所有的节点。

Custom SIGINT Handler

#include <ros/ros.h>
#include <signal.h>

void mySigintHandler(int sig)
{
  // Do some custom action.
  // For example, publish a stop message to some other nodes.
  
  // All the default sigint handler does is call shutdown()
  ros::shutdown();
}

int main(int argc, char** argv)
{
  ros::init(argc, argv, "my_node_name", ros::init_options::NoSigintHandler);
  ros::NodeHandle nh;

  // Override the default ros sigint handler.
  // This must be set after the first NodeHandle is created.
  signal(SIGINT, mySigintHandler);
  
  //...
  ros::spin();
  return 0;
}

注: 当程序捕捉到ctrl + c之后,会进入信号处理函数,处理完后会终端ros节点。

如何使用shutdown()终止所有的节点

在launch文件中,有个required参数,设为true时,当该节点shutdown后,其余节点也会被shutdown。

required="true"(optional)
  If node dies, kill entire roslaunch.

注:这个功能在程序中还是很有用的。

参考

Initialization and Shutdown

roslaunch/xml/node

原文地址:https://www.cnblogs.com/ChrisCoder/p/10116191.html