- 论坛徽章:
- 1
|
回复 #1 sosogh 的帖子
貌似这个问题用perl的多线程模式实现比较好
为了使得显示结果效果更好,稍微用了一点点技巧
1 #!/usr/bin/perl
2 use strict;
3 use warnings;
4 use threads;
5 use Net::Ping;
6 my $complete_IP = '10.1.1.255'; #用了一个不存在的ip试验timeout
7 my $p = Net::Ping->new("icmp");
8 $p->hires(1);
9 $|=1;
10 sub myping() {
11 my ($sec,$min,$hour,$mday,$mon,$year,$wday,$yday,$isdst)=localtime;
12 my $cur_time = sprintf "%4d-%02d-%02d %02d:%02d:%02d",
13 $year+1900,$mon+1,$mday,$hour,$min,$sec;
14 print "$cur_time PingTime --> ";
15 my $pid = fork();
16 if ( not defined $pid ) {
17 warn "cannot fork";
18 }elsif ( $pid == 0 ) {
19 print "Time out";
20 my @resp = $p->ping($complete_IP,3);
21 if ( $resp[0] ) {
22 my $ms = $resp[1] * 1000;
23 my $pingtime = sprintf "%.2f" , $ms;
24 print "\r$cur_time PingTime --> $pingtime ms ";
25 }else{
26 # $result="Time out";
27
28 }
29 exit(0);
30 }else{
31 waitpid($pid,0);
32 }
33 }
34 while(1){
35 print "\n";
36 threads->create(\&myping);
37 sleep (1);
38 my @threads = threads->list();
39 #warn $#threads;
40 foreach (@threads){
41 $_->detach();
42 }
43 }
44 |
|