多进程接收socket数据的问题
在主函数中创建一个子进程,子进程负责接收socket连接并处理,父进程处理其他事务,但是子进程只能接收一次数据,第二次的就接收不到了,是什么问题?如何让子进程可以一直接收?高手赐教
主函数如下:
int main(int argc, char** argv)
{
int pid;
pid = fork();
//child process handle the connections
if(pid == 0)
{
recvConnecttion();
}
else if(pid > 0)
{
//do other things
}
else
return -1;
}
//modify this function
int recvConnecttion()
{
struct sockaddr_in sin;
struct sockaddr_in rin;
int sock_fd;
int address_size;
char buf[80];
char str[INET_ADDRSTRLEN];
int i;
int len;
int n;
char *recvBuf=NULL;
bzero(&sin, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = INADDR_ANY;
sin.sin_port = htons(7980);
sock_fd = socket(AF_INET, SOCK_DGRAM, 0);
if (-1 == sock_fd)
{
perror("create socket error");
exit(1);
}
n = bind(sock_fd, (struct sockaddr *)&sin, sizeof(sin));
if (-1 == n)
{
perror("bind error");
exit(1);
}
while(1)
{
recvBuf = (char *)malloc(MSG_LEN);
address_size = sizeof(rin);
n = recvfrom(sock_fd, recvBuf, MSG_LEN, 0, (struct sockaddr *)&rin, &address_size);
if (-1 == n)
{
perror("recvfrom error.\n");
exit(1);
}
NMSG_T tmp;
memset(&tmp,0,sizeof(NMSG_T));
memset(tmp.msg_data,0,MSG_BUF_LEN);
memcpy(&tmp,recvBuf,MSG_LEN);
printf("msg type = %d\n", MSG_INFO_PUB);
printf("msg sub = %d\n", tmp.msg_sub);
if(tmp.msg_type == MSG_INFO_PUB)
{
char new_sec[20];
char *secs[300];
for(i=0;i<300;i++)
{
secs[i] = (char *)malloc(MAX_CFG_BUF);
}
int secs_num = ConfigGetSectionsInArray("info.cfg", secs);
sprintf(new_sec,"info%d", secs_num);
ConfigSetKey("info.cfg", new_sec, "detail", tmp.msg_data);
ConfigSetKey("info.cfg", new_sec, "type", tmp.msg_sub);
for(i=0;i<300;i++)
{
if(secs[i])
free(secs[i]);
}
}
}
}
------解决方案--------------------recvfrom 是面向无连接的
不过问题应该和这个无关。
楼主确认第一次接收数据后,还有第二次三次数据过来?
------解决方案--------------------先加个打印,在recvfrom后面打印出recvBuf的内容
如果第二次还没有内容,就抓个网络包看一下
还有你这个recvBuf每次收之前应该都要memset 0一下