perlshellloopssleepusleep

Simple PERL script to loop very quickly


I'm trying to get a perl script to loop very quickly (in Solaris).

I have something like this:

#! /bin/perl

while ('true')
{
 use strict;
 use warnings;
 use Time::HiRes;

 system("sh", "shell script.sh");
 Time::HiRes::usleep(10);
}

I want the perl script to execute a shell script every 10 microseconds. The script doesn't fail but no matter how much I change the precision of usleep within the script, the script is still only being executed approx 10 times per second. I need it to loop much faster than that.

Am I missing something fundamental here? I've never used perl before but I can't get the sleep speed I want in Solaris so I've opted for perl.

TIA

Huskie.

EDIT:

Revised script idea thanks to user comments - I'm now trying to do it all within perl and failing miserably! Basically I'm trying to run the PS command to capture processes - if the process exists I want to capture the line and output to a text file.

#! /bin/perl

while ('true')
{
 use strict;
 use warnings;
 use Time::HiRes;

 open(PS,"ps -ef | grep <program> |egrep -v 'shl|grep' >> grep_out.txt");
 Time::HiRes::usleep(10);
}

This returns the following error:

Name "main::PS" used only once: possible typo at ./ps_test_loop.pl line 9.

Solution

  • This is a pure perl program (not launching any external process) that looks for processes running some particular executable:

    #!/usr/bin/perl
    
    use strict;
    use warnings;
    
    my $cmd = 'lxc-start';
    
    my $cmd_re = qr|/\Q$cmd\E$|;
    
    $| = 1;
    
    while (1) {
        opendir PROC, "/proc" or die $!;
        while (defined(my $pid = readdir PROC)) {
            next unless $pid =~ /^\d+$/;
            if (defined(my $exe = readlink "/proc/$pid/exe")) {
                if ($exe =~ $cmd_re) {
                    print "pid: $pid\n";
                }
            }
        }
        closedir PROC;
        # sleep 1;
    }
    

    On my computer this runs at 250 times/second.