gpt4 book ai didi

multithreading - Perl多线程-在第一个线程成功时退出

转载 作者:行者123 更新时间:2023-12-03 13:00:44 24 4
gpt4 key购买 nike

我绝不是Perl或多线程专家,但是我坚信我“做错了”,并且需要一些有关如何更改它的指导,这样我才不会收到线程退出警告。

如您所见,该程序读入参数0,进行查找以找到与主机名关联的每个IP地址,然后测试每个IP以查看ssh是否正在运行。

该脚本的目的是为每个主机生成一个tcp测试,并返回第一个成功的tcp连接。

谁能建议一种更可靠且不需要 sleep 的方法?

use strict;
use warnings;
BEGIN {
use Config;
$Config{useithreads} or die('Recompile Perl with threads to run this program.');
}
use threads;
use IO::Socket::INET;
$| = 1;

unless($ARGV[0]){ die("error please use argument")}

my $timeoutval=3;
my $testHost=$ARGV[0];
my $dlquery=`dig $testHost | grep 'IN A'`;
my $SUCCESS=0;

sub testSSHhost {
my $fqdn = shift;
my $socket = new IO::Socket::INET (
PeerHost => $fqdn,
PeerPort => '22',
Proto => 'tcp',
Timeout => $timeoutval,
) or return "ERROR in Socket Creation : $!\n";

my $tcpData = <$socket>;
$socket->close();
if ($tcpData && $tcpData=~/SSH/){
print "$fqdn\n";
$SUCCESS=1;
exit(0);
}
return $fqdn;
}

my @threads;
for my $line (split(/\n/,$dlquery)){
my @linesplit=split(/ /,$line);
$linesplit[0]=~s/\.$//;
$linesplit[0]=~s/ *//g;
my $t = threads->new(\&testSSHhost, $linesplit[0]);
push(@threads,$t);
}

while (!$SUCCESS){sleep 0.3}

我真正要避免的是“正在运行2个线程时退出了一个线程”。错误信息
或“分段故障”消息

最佳答案

这样的事情(未测试!):

use Modern::Perl;
use threads;
use Thread::Queue;
use IO::Socket::INET;
$| = 1;

my $testHost = $ARGV[0];
my $dlquery = `dig $testHost | grep 'IN A'`;
my $config = { NUMBER_OF_THREADS => 5 }; #how many threads you gonna use?

my $queue = Thread::Queue->new;
my $queue_processed = Thread::Queue->new;

for my $line ( split( /\n/, $dlquery ) ) {
my ($ip) = split( / /, $line );
$ip =~ s/\.$//;
$ip =~ s/ *//g;

$queue->enqueue($ip);
}

foreach my $thread_id ( 1 .. $config->{NUMBER_OF_THREADS} ) {

$queue->enqueue(undef);
my $thread = threads->create( \&testSSHhost() )->detach();
}

while ( $queue->pending() ) {

my $result = $queue_processed->dequeue();

if ( $result->{status} ) {

say $result->{ip};
}
}

sub testSSHhost {

while ( my $fqdn = $queue->dequeue() ) {

my $status = 0;

my $socket = new IO::Socket::INET(
PeerHost => $fqdn,
PeerPort => 22,
Proto => 'tcp',
Timeout => 3,
) or return "ERROR in Socket Creation : $!\n";

my $tcpData = <$socket>;
$socket->close();
if ( $tcpData && $tcpData =~ /SSH/ ) {

$status = 1;
}

$queue_processed->enqueue( { ip => $fqdn, status => $status, } );
}

return 0;
}

关于multithreading - Perl多线程-在第一个线程成功时退出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11157928/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com