当前位置: 技术问答>linux和unix
多进程接收socket数据的问题
来源: 互联网 发布时间:2016-08-15
本文导语: 在主函数中创建一个子进程,子进程负责接收socket连接并处理,父进程处理其他事务,但是子进程只能接收一次数据,第二次的就接收不到了,是什么问题?如何让子进程可以一直接收?高手赐教 主函数如下: int ma...
在主函数中创建一个子进程,子进程负责接收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 = %dn", MSG_INFO_PUB);
printf("msg sub = %dn", tmp.msg_sub);
if(tmp.msg_type == MSG_INFO_PUB)
{
char new_sec[20];
char *secs[300];
for(i=0;i
主函数如下:
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 = %dn", MSG_INFO_PUB);
printf("msg sub = %dn", tmp.msg_sub);
if(tmp.msg_type == MSG_INFO_PUB)
{
char new_sec[20];
char *secs[300];
for(i=0;i