ROS Resources: Documentation | Support | Discussion Forum | Index | Service Status | ros @ Robotics Stack Exchange
Ask Your Question

How to spawn a new node from inside C++ code

asked 2015-04-10 14:35:27 -0500

Jordan9 gravatar image

I'm using the gazebo_ros package, which is an interface for using ROS with the Gazebo simulation software. On their relevant documentation page, they say that the best way to dynamically create a new model in the simulation is to run the node for spawning models:

rosrun gazebo_ros spawn_model -database coke_can -sdf -model coke_can3 -y 2.2 -x -0.3

This node functions as a wrapper that will get XML from the database and load it, etc. My question is, is there a way to run this node with the command above, but from the C++ code of an already-running ROS node? i.e. to add models dynamically, once the controller node is already running.

edit retag flag offensive close merge delete

2 Answers

Sort by ยป oldest newest most voted

answered 2015-04-16 16:14:30 -0500

Jordan9 gravatar image

In light of no better answer being given, I'll show my hacky workaround. It was as simple as just using the system() function built into C++ for use on linux systems.

system("rosrun gazebo_ros spawn_model -database coke_can -sdf -model coke_can3 -y 2.2 -x -0.3");

edit flag offensive delete link more

answered 2015-04-11 07:52:14 -0500

timm gravatar image

updated 2015-04-11 07:52:43 -0500

The easiest way to dynamically spawn a model from your code is to call the spawn_model ROS service offered by gazebo_ros, which essentially is the same what the spawn_model node does internally. I.e. instead of running the spawn_model node, you call the spawn_model service.

You can see here how the corresponding service interface is defined. Use rosservice list to find the correct name of the service instance while you have your Gazebo instance running.

Tutorials for writing a service client (which is very easy and similar to writing a ROS publisher) can be found here:
C++ service client tutorial
Python service client tutorial

edit flag offensive delete link more


I originally tried to use the spawn_model service. The thing is, the spawn_model wrapper node has the functionality of pulling the XML for the model from the online database, so I don't have to specify it manually when I create the srv object for calling the service. That is what I need.

Jordan9 gravatar image Jordan9  ( 2015-04-15 10:34:54 -0500 )edit

Mmmkay, I can't accept this answer because it doesn't actually address the general question of whether it's possible to spawn a new ROS node from inside the code of another node.

Jordan9 gravatar image Jordan9  ( 2015-04-16 16:15:31 -0500 )edit

Question Tools

1 follower


Asked: 2015-04-10 14:35:27 -0500

Seen: 2,420 times

Last updated: Apr 16 '15