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

Handling SIGINT

asked 2012-04-10 05:59:09 -0500

erpa gravatar image

updated 2014-01-28 17:11:55 -0500

ngrennan gravatar image

Hi, I was trying to write a node acting as a tcp server, my first try (to see if evrythin worked) is the following

#include "iostream"
#include "vector"
#include "string"
#include "ros/ros.h"
#include "netinet/in.h"

using namespace std;

int main(int argc, char **argv)
  ros::init(argc, argv, "cobot_service_test");
  ros::NodeHandle n;

  int sockfd, newsockfd, portno;
  socklen_t clilen;
  char buffer[1024];
  struct sockaddr_in serv_addr, cli_addr;
  int ns;

  sockfd = socket(AF_INET, SOCK_STREAM, IPPROTO_TCP);
  bzero((char *) &serv_addr, sizeof(serv_addr));
  portno = 27015;
  serv_addr.sin_family = AF_INET;
  serv_addr.sin_addr.s_addr = INADDR_ANY;
  serv_addr.sin_port = htons(portno);

  if (bind(sockfd, (struct sockaddr *) &serv_addr, sizeof(serv_addr)) < 0)
      perror("ERROR on binding");

  printf("Starting the server\n");
  clilen = sizeof(cli_addr);
  newsockfd = accept(sockfd, NULL, NULL);

  if (newsockfd < 0)
      perror("ERROR on accept");

      ns = recv(newsockfd,buffer,1023, 0);
      if (ns < 0)
          perror("ERROR reading from socket\n");
      if (ns > 0)
          printf("Message received: %s\n",buffer);

  return 0;

This works fine as server the problem is that I cant stop it using ctrl-c (but if i use the same code without ROS I can). I think I'm missing something on how ros::spin works but I really didn't understood how I'm supposed to use it. Thanks a lot for your help!

edit retag flag offensive close merge delete



...why are you writing a TCP server? The whole point of ROS messages is to let you skip all of that...

Mac gravatar image Mac  ( 2012-04-10 07:00:45 -0500 )edit

because i need it to get messages from another pc running windows

erpa gravatar image erpa  ( 2012-04-10 07:03:32 -0500 )edit

Ok, good reason. Painful to have to do this by hand, though.

Mac gravatar image Mac  ( 2012-04-10 08:09:15 -0500 )edit

Now I am facing the same problem just like yours, I wonder how did you solve it? Many thanks:-)

wdsky2010 gravatar image wdsky2010  ( 2015-11-15 20:54:05 -0500 )edit

1 Answer

Sort by ยป oldest newest most voted

answered 2012-04-10 07:18:00 -0500

joq gravatar image

You might need to add a ros::spinOnce() in your main loop.

edit flag offensive delete link more


you mean in the while(ros::ok) loop?

erpa gravatar image erpa  ( 2012-04-10 07:33:04 -0500 )edit

Yes. spinOnce processes all pending ROS events. Alternatively you can use an AsyncSpinner. See here:

Lorenz gravatar image Lorenz  ( 2012-04-10 07:38:55 -0500 )edit

Question Tools


Asked: 2012-04-10 05:59:09 -0500

Seen: 1,377 times

Last updated: Nov 15 '15