所有任务完成之前,线程代码都会退出

时间:2017-07-28 13:26:37

标签: multithreading perl

我正在尝试获取现有脚本的一部分,并让它同时运行多个nmap扫描,以提高脚本的速度。

我最初尝试使用fork,但有人建议我应该使用线程,因为我在Windows机器上这样做。我修改了一个我在网上找到的代码片段,它部分有用。

我正在使用23个IP地址的列表。我已经能够打开10个线程并扫描前10个地址,但随后代码退出。理想情况下,代码会在每次退出时打开一个新线程,以便始终运行10个线程,直到达到其余部分,在这种情况下会有三个。然后只打开3个线程。

这整个代码需要在我原始顺序代码中的子程序中运行。我使用ping而不是nmap命令来测试。

#!/usr/bin/Perl

use strict;
use threads;

my $i = 0;
my @lines;

# Define the number of threads
my $num_of_threads = 10;

# use the initThreads subroutine to create an array of threads.
my @threads = initThreads();

my @files = glob( "./ping.txt" ) or die "Can't open CMS HostInventory$!";     # Open the CMS Host Inventory csv files for parsing

foreach my $file ( @files ) {
    open (CONFIG, '<', $file) or die "Can't ip360_DNS File$!";
    @lines = <CONFIG>;
    chomp (@lines);
}

# Loop through the array:
foreach ( @threads ) {
        # Tell each thread to perform our 'doOperation()' subroutine.
    $_ = threads->create(\&doOperation);
}

# This tells the main program to keep running until all threads have finished.
foreach ( @threads ) {
    $_->join();
}

print "\nProgram Done!\nPress Enter to exit";
$a = <>;

####################### SUBROUTINES ############################

sub initThreads{

    my @initThreads;

    for ( my $i = 1; $i <= $num_of_threads; $i++ ) {
        push(@initThreads, $i);
    }

    return @initThreads;
}


sub doOperation{

    # Get the thread id. Allows each thread to be identified.
    my $id = threads->tid();
    my $ip = ($id - 1);

    system("ping $lines[$ip] >> ./input/$lines[$ip].txt");
    print "Thread $id done!\n";

    # Exit the thread
    threads->exit();
}

0 个答案:

没有答案