socket中关于"Bad file descriptor"(内有程序)
我的大体思路是这样:文件A中有大量IP地址,此程序从中读取,然后循环调用线程子函数进行ping操作。我遇到的问题是:经常到100多个线程的时候就会出现recv:Bad file descriptor,或者是connect:Bad file descriptor。
求助各位大侠
/*创建线程*/
for(i=0;i<SIZE;i++)
{
fscanf(fp1," %s",&c);
if(feof(fp1)) {fclose(fp1);exit(0);}
dst_ip =c;
int temp;
memset(&thread, 0, sizeof(thread));
if((temp = pthread_create(&thread, NULL, thread1, NULL)) != 0)
{sprintf(str3,"线程%d创建失败!\n",i);
printf("%s",str3);}
else
{sprintf(str3,"线程%d创建成功!\n",i);
printf("%s",str3);}
usleep(15000);//
}
int ss;
for(ss=0;ss<SIZE;ss++)
{
pthread_join(thread,NULL);
{sprintf(str3,"线程%d结束!\n",ss);
printf("%s",str3);}
}
/线程子程序/
//线程函数
void *thread1()
{
struct sockaddr_in sin;
//创建通信所需套接字,注意套接字类型为原始套接字
if ((sockfd = socket(PF_INET, SOCK_RAW, IPPROTO_ICMP)) < 0) {
perror("socket");
exit(1);
}
tmp = 1;
setsockopt(sockfd, 0, IP_HDRINCL, & tmp, sizeof(tmp));
memset(sendbuf, 0, sizeof(sendbuf));
memset(& sin, 0, sizeof(sin));
sin.sin_family = AF_INET;
sin.sin_addr.s_addr = inet_addr(dst_ip);
if(connect(sockfd,(struct sockaddr*)&sin,sizeof(struct sockaddr)) == -1)
{perror ("connect");
exit(1);
}
recvbuf_size = sizeof(struct iphdr) + sizeof(struct icmphdr)+sizeof(struct timeval);
sendbuf_size=pack(dst_ip);
// usleep(500000);//0.5s
if (sendto(sockfd, sendbuf, sendbuf_size, 0, (struct sockaddr *) &sin,sizeof(struct sockaddr_in)) < 0)
{
perror("sendto");
}
length = sizeof(sin);
//signal(SIGALRM,handler);
//alarm(WAIT_TIME);
if (recvfrom(sockfd, recvbuf, recvbuf_size, 0, (struct sockaddr *) &sin, &length) < 0) {
perror("recvfrom");
exit(0);}
gettimeofday(&tvrecv,NULL);
//显示报文信息
unpack(recvbuf,recvbuf_size,(struct sockaddr_in *)&sin);
close(sockfd);
usleep(7000);//0.5s
//sleep(1);//1s
pthread_exit(NULL);}