Public
Snippet $1655253 authored by Jesse

Perl script to execute "xbps-remove -o" and "xbps-remove -O" using threads

Edited
xbps-threaded-cleanup.pl
#!/usr/bin/env perl

######################################################################
# File: xbps-threaded-cleanup.pl
# Language: Perl
# Version: 0
# Author: culb (nightfrog)
# Contact: the01culb[at]gmail[dot]com
# Usage: sudo xbps-threaded-cleanup
# Purpose:Run xbps-remove (-o && -O)
#
# Resources: http://perldoc.perl.org/Thread.html
#            http://perldoc.perl.org/Thread/Queue.html
#            http://perldoc.perl.org/functions/system.html
#
# Note: This is a threaded version of the original xbps-cleanup script
######################################################################

use strict;
use warnings;
use threads;
use Thread::Queue;

# Start a queue
my $queue = Thread::Queue->new();

# Push the command into the queue
for my $command ( 'xbps-remove -o', 'xbps-remove -O' )
{
    $queue->enqueue( $command );
}

#print $queue->pending() . "\n";

# Store the threads in an array to join later
my @thread = map
{
    threads->create( sub
    {
        # Pull the commands from the queue (non-blocking)
        while( defined( my $item = $queue->dequeue_nb() ) )
        {
            print "\e[34m### Beginning of $item ###\033[0m\n";
            if( system( $item ) != 0 )
            {
                if( $? == -1 )
                {
                    print "\e[31m Failed to execute: $!\033[0m\n";
                }
                elsif( $? & 127 )
                {
                    printf "\e[31mChild died with signal %d, %s coredump\033[0m\n",
                           ( $? & 127 ),  ( $? & 128 ) ? 'with' : 'without';
                }
                else
                {
                    printf "\e32m Child exited with value %d\033[0m \n", $? >> 8;
                }
            }
            print "\e[34m### End of $item ###\033[0m\n";
        }
    });
} 1 .. $queue->pending();# pending() is the actual count from 1, not from 0. Should be 2

for my $eachThread( @thread )
{
    $eachThread->join();
}