免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 2491 | 回复: 3
打印 上一主题 下一主题

多线程ping [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2007-02-07 14:05 |只看该作者 |倒序浏览
ping.pl

  1. #!/usr/bin/perl -w
  2. use strict;
  3. use Net::Ping;
  4. use threads;
  5. use threads::shared;

  6. my @host = split(/\./,$ARGV[0]);
  7. $SIG{ALRM} = sub {print "time out\n"};   #不加这个会出现Alarm clock,加上了没反应
  8. my $next:shared = 1;                       #说明$next是个共享的变量,似乎必须要加
  9. sub my_ping(){
  10.     my @ip = @host;
  11.     my $p = Net::Ping->new();

  12.     {lock $next;$ip[3]=$next;$next++};    #对$next加锁
  13.     while($ip[3] <= 254){
  14.         my $remote_ip = join(".",@ip);
  15.         #print "$remote_ip\n";
  16.         print "$remote_ip is alive.\n" if $p->ping($remote_ip);
  17.         {lock $next;$next++;$ip[3]=$next};
  18.         sleep(1);
  19.     }

  20.     $p->close();
  21. }
  22. my $max_thread = 10;
  23. my @t;
  24. while($max_thread-- > 0){
  25.     push @t,threads->new(\&my_ping);        #创建新线程
  26. }
  27. for(@t){
  28.     print "..\n";                                    #有线程退出了
  29.     $_->join;
  30. }
复制代码


用法:
./ping.pl 192.168.0.1
将依次的ping 192.168.0.1 ~ 192.168.0.254

搞了一下午,还是没明白 use Thread; 和 use threads;有什么区别,
不过总算是能用了,呵呵

论坛徽章:
0
2 [报告]
发表于 2007-02-07 18:02 |只看该作者
线程是有问题的
在centos3,centos4跑一下,就出来问题的!

论坛徽章:
0
3 [报告]
发表于 2007-02-07 18:07 |只看该作者
CLONE_THREAD
              (Linux 2.4 onwards) If CLONE_THREAD is set, the child  is  placed  in  the
              same thread group as the calling process.

              If  CLONE_THREAD  is  not  set,  then the child is placed in its own (new)
              thread group, whose ID is the same as the process ID.

              (Thread groups are feature added in Linux 2.4 to support the POSIX threads
              notion  of  a set of threads sharing a single PID.  In Linux 2.4, calls to
              getpid(2) return the thread group ID of the caller.)

论坛徽章:
0
4 [报告]
发表于 2007-02-08 08:34 |只看该作者
谢谢楼上提醒,没想那么多。
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP