problem with publish in fork() process
When I use fork() function, then the publish function of Publisher do not work, do any one who has met this problem, I am grateful that you can tell me something, thanks :-) the code
#include "ros/ros.h"
#include "std_msgs/String.h"
#include <sstream>
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
void error(const char *msg)
{
perror(msg);
exit(1);
}
/**
* This tutorial demonstrates simple sending of messages over the ROS system.
*/
int main(int argc, char **argv)
{
ros::init(argc, argv, "talker");
ros::NodeHandle nh;
ros::Publisher chatter_pub = nh.advertise<std_msgs::String>("chatter", 1000);
int sockfd, newsockfd, portno, pid;
socklen_t clilen;
struct sockaddr_in serv_addr, cli_addr;
if (argc < 2) {
fprintf(stderr,"ERROR, no port provided\n");
exit(1);
}
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0)
error("ERROR opening socket");
bzero((char *) &serv_addr, sizeof(serv_addr));
portno = atoi(argv[1]);
//portno = 8888;
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)
error("ERROR on binding");
listen(sockfd,5);
clilen = sizeof(cli_addr);
while(ros::ok())
{
newsockfd = accept(sockfd, (struct sockaddr *) &cli_addr, &clilen);
if (newsockfd < 0)
error("ERROR on accept");
pid = fork();
if (pid < 0)
error("ERROR on fork");
if (pid == 0) {
close(sockfd);
std_msgs::String msg;
//ros::NodeHandle nh;
//ros::Publisher chatter_pub = nh.advertise<std_msgs::String>("chatter", 1000);
int n;
char buffer[256];
//while(ros::ok())
//{
bzero(buffer,256);
n = read(newsockfd,buffer,255);
if (0 > n) error("ERROR reading from socket");
else if(0 < n)
{
msg.data = buffer;
ROS_INFO("%s", msg.data.c_str());
chatter_pub.publish(msg);
printf("Here is the message: %s\n",buffer);
n = write(newsockfd,"I got your message",18);
if (n < 0) error("ERROR writing to socket");
}
else ;
//dostuff(newsockfd, chatter_pub);
exit(0);
}
else close(newsockfd);
}
close(sockfd);
return 0;
}