I would assume that "system is out to get you", so you should just assume that trying to read files will fail, but what exactly will happen doesn't matter.
For example, when you open file or next FILE, I would instead rerun glob and try again (to protect from files removed in /usr/bin - you wouldn't want this to reboot system, right?). As for basic idea, I've something similar to your script except more... paranoic (when something will go wrong, it will reboot). You don't need to know what will happen when EIO will appear - some condition in the code (or autodie pragma) will catch something is wrong (what exactly is wrong doesn't matter).
#!/usr/bin/perl
# License: Do what you want with this code snippet. You could even
# claim it as yours and remove this license. I don't care.
# Automatically die when something goes wrong
use autodie;
use constant DIRECTORY => '/usr/bin';
use strictures 1;
use Try::Tiny;
my @files;
sub glob_files {
my ($directory) = @_;
opendir( my $dh, $directory );
# On my system, /usr/bin has directories such as /usr/bin/X11
return grep { -f "$directory/$_" } readdir $dh or die "Empty glob"
+;
}
sub try_random_file {
my ($file) = @_;
open my $fh, '<', $file;
# Four bytes should be enough to determine if stuff works
read $fh, my $buffer, 4;
# Shouldn't happen
if ( length $buffer != 4 ) {
die 'File is too small.';
}
}
sub reboot {
my ($error) = @_;
exec '/var/tmpfs/reboot', '-nf';
}
@files = glob_files DIRECTORY;
while (1) {
try {
my $file = $files[ int rand @files ];
try {
try_random_file DIRECTORY . "/$file";
}
catch {
# If file doesn't exist then it was possibly deleted.
# Reglob everything and try again with other file. If
# it won't work then something is simply broken.
die $_ if -f $file;
@files = glob_files DIRECTORY;
try_random_file DIRECTORY . "/$files[ int rand @files ]";
}
}
catch {
reboot $_;
};
# Usually, you should sleep just so script won't take entire CPU
sleep 15;
}
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|