正好公司为了检测前台网络,力图收集有力证据与某CDN PK,所以随手写了一个群PING的程序。
写的内容比较简单,没有去特别追求线程效率,也没有去用LINUX 2.6+的殿堂级神器,以追求实现效率为主,一些参数大家可以自己调。
同事后来帮忙补了些日志处理,当然如果有兴趣的,还可以直接与AS3做SOCKET展示。
大致的源码如下:
#Linux REHL 6,x64,4C/32G,GCC
#define MAXTD 2
#include <stdio.h>
#include <string.h>
#include <pthread.h>
#include <stdlib.h>
char IP[230][30];
char *PINGI=NULL;
char *PINGC=NULL;
char *PINGS=NULL;
void *dmlog();
int main(int argc,char *argv[])
{
FILE *fp=NULL;
char *tmpstr=NULL;
char *ipraw;
pthread_t dm[230];
pthread_attr_t attr={0};
int t=0;
if(argc!=4)
{
printf("Not Enough Parameters!,GoodBye Exit(0)!\n");
printf("Or you can try example below:\n");
printf("ping 1 5 300 \n");
printf("Just 1 mens interval\n");
printf("5 means 5 packets\n");
printf("300 menas 300 packet size\n");
exit(0);
}
printf("%s\n",argv[1]);
printf("%s\n",argv[2]);
printf("%s\n",argv[3]);
fp=fopen("./ping.cnf", "r");
PINGI=(char*)malloc(sizeof(char)*10);
PINGC=(char*)malloc(sizeof(char)*2);
PINGS=(char*)malloc(sizeof(char)*10);
tmpstr=(char*)malloc(sizeof(char)*30);
ipraw=(char*)malloc(sizeof(char)*30);
strcpy(PINGI,argv[1]);
strcpy(PINGC,argv[2]);
strcpy(PINGS,argv[3]);
pthread_attr_init (&attr);
pthread_attr_setscope (&attr, PTHREAD_SCOPE_SYSTEM);
pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
printf("Here Start Ping Test\n");
printf("Create Thread\n\n\n");
while(fgets(tmpstr,100,fp)!=NULL)
{
sscanf(tmpstr,"%[^\n]",ipraw);
if(strlen(ipraw)!=0)
{
strcpy(IP[t],ipraw);
pthread_create(&dm[t],NULL,(void*)dmlog,(void*)t);
printf("fun:%s,%d,%d,%s\n",ipraw,t,strlen(ipraw),IP[t]);
t++;
}
}
printf("Create Thread Done!\n");
while(1)
{
sleep(8);
printf("I've finished my job ,I wanna go...\n");
exit(0);
}
close(fp);
free(tmpstr);
free(ipraw);
free(PINGI);
free(PINGC);
free(PINGS);
}
void *dmlog(int ag)
{
char *text=NULL;
text=(char *)malloc(sizeof(char)*200);
strcpy(text,"ping -w 6 -i ");
strcat(text,PINGI);
strcat(text," -c ");
strcat(text,PINGC);
strcat(text," -s ");
strcat(text,PINGS);
strcat(text," ");
strcat(text,IP[ag]);
strcat(text," |tee ./logs/");
strcat(text,IP[ag]);
strcat(text,".log");
//printf("PID:%d,THID:%lu,TEXT:%s,ARG:%s\n",getpid(),(unsigned int)pthread_self(),text,IP[ag]);
//printf("%s\n",text);
system(text);
free(text);
}