Consider the following example:
#include <ros/ros.h>
#include <std_msgs/String.h>
void connectCallback(const ros::SingleSubscriberPublisher&)
{
ROS_INFO("connectCallback");
}
void disconnectCallback(const ros::SingleSubscriberPublisher&)
{
ROS_INFO("disconnectCallback");
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "test_node");
ros::NodeHandle nh;
ros::Publisher pub = nh.advertise<std_msgs::String>("talk", 1, &connectCallback, &disconnectCallback);
ros::Rate r(1);
while (nh.ok())
{
ROS_INFO("Number of subscribers: %zu", pub.getNumSubscribers());
ros::spinOnce();
r.sleep();
}
return 0;
}
When subscribing using rostopic echo /talk
, connectCallback
is called immediately. However, when shutting down the rostopic
process, the reported number of subscribers is still 1 until disconnectCallback
gets called about one minute later. Why? Is there any way to shorten this timeout?
When the publisher is active (i.e. publishing something in the loop), disconnectCallback
is called immediately.
EDIT
Here is another subscriber (different from rostopic
) that I used for testing with the same result:
#include <ros/ros.h>
#include <std_msgs/String.h>
void callback(const std_msgs::StringConstPtr& msg)
{
std::cout << msg->data << std::endl;
}
int main(int argc, char **argv)
{
ros::init(argc, argv, "subscriber");
ros::NodeHandle nh;
ros::Subscriber sub = nh.subscribe("talk", 1, &callback);
ros::Time start_time = ros::Time::now();
while (ros::ok() && (ros::Time::now() - start_time).toSec() < 10)
{
ros::spinOnce();
}
return 0;
}
Originally posted by Stephan on ROS Answers with karma: 1924 on 2012-01-17
Post score: 2
Original comments
Comment by Stephan on 2012-01-18:
@Lorenz: I tried that already, I'll edit the question to clarify this.
Comment by Lorenz on 2012-01-17:
I would guess that the rostopic process does not shutdown correctly and after a minute, your node notices that the socket is invalid. I would write a simple roscpp node that subscribes, stays connected for a while and then shuts down. If that works, you know it's rostopic's fault.
Comment by Stephan on 2012-01-17:
I just tried using a self-made subscriber, same result.
Comment by dornhege on 2012-01-17:
One guess would be that shutting down rostopic doesn't properly close the connection (although it should), so only when you try to publish the node realizes it's disconnected