int sockfd,newsockfd;
int ret;
int ret1;
struct sockaddr_in my_addr,their_addr;
sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd == -1)
{
perror("socket");
exit(1);
}
my_addr.sin_family = AF_INET;
my_addr.sin_port = htons(6006);
my_addr.sin_addr.s_addr = inet_addr("192.168.9.140");
bzero(&(my_addr.sin_zero), 8);
if ((bind(sockfd, (struct sockaddr *) &my_addr, sizeof(struct sockaddr)))== -1)
{
perror("bind");
close(sockfd);
exit(1);
}
ret1=listen(sockfd,20);
if(ret1==-1)
{
perror("listen");
printf("listening:%d",ret1);
exit(1);
}
char buf[100<<10];
//char *new_buf;
//int total=0;
do
{
unsigned int addr_len = sizeof(struct sockaddr);
if ((newsockfd = accept(sockfd, (struct sockaddr *) &their_addr, &addr_len)) < 0)
{
perror("accept");
continue;
}
else
{
printf("accepted a new connecttion.\n");
pid_t fpid; //fpid表示fork函数返回的值
fpid = fork();
if (fpid < 0)
{
printf("error in fork!");
}
else if (fpid == 0)
{
printf("i am the child process, my process id is %d\n",getpid());
fd_set rfd;
struct timeval timeout;
timeout.tv_sec = 30;
timeout.tv_usec = 0;
FD_ZERO(&rfd);
FD_SET(newsockfd,&rfd);
if ((select(newsockfd + 1, &rfd, NULL, NULL, &timeout)) == -1)
perror("select");
else if ((select(newsockfd + 1, &rfd, NULL, NULL, &timeout)) == 0)
{
printf("time out\n");
close(newsockfd);
}
else
{
memset(buf, 0, sizeof(buf));
ret = recv(newsockfd, buf, 100 << 10, 0);
if (ret == -1)
{
perror("recv");
close(newsockfd);
exit(1);
}
else
{
xedex_t *dex_p = (xedex_t *) buf;
frame_seq = dex_p->U.frame.seq;
frame_date_len=dex_p->U.frame.data_len;
printf("frame_seq=%d,frame_date_len=%d,ret=%d\n",frame_seq,frame_date_len,ret);
}
}
else
{
printf("i am the parent process, my process id is %d\n",getpid());
close(newsockfd);
}
}
} while (1); |