Advertisement
DRVTiny

mmap_server.pl

Mar 2nd, 2018
446
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Perl 1.64 KB | None | 0 0
  1. #!/usr/bin/perl
  2. use 5.16.1;
  3. use strict;
  4. use warnings;
  5. use constant {
  6.     DFLT_SER_TAG        => 'CB',
  7.     N_PERC_RED          =>  15,
  8. };
  9. use subs qw(store_data);
  10.  
  11. use File::Slurp qw(write_file);
  12. use File::Map qw(map_file);
  13. use AnyEvent;
  14. use Try::Tiny;
  15. use Tag::DeCoder;
  16.  
  17. my %hsh=map {'t'.$_ => {'triggerid'=>$_, 'status'=>(int(rand 25) & 1), 'lostfunk'=>rand(),'svc-path'=>[map [map int(rand 10000), 2..(int(rand 5)+2)], 0..int(rand 5)]}} 1..10000;
  18.  
  19. my $pthMapFile='/tmp/test.mmap.'.$$;
  20.  
  21. # Initialy write data to the file that will be mmap'ed later
  22. store_data($pthMapFile, \%hsh);
  23.  
  24. # Save mmaped file name
  25. write_file '/tmp/mmaped_file.pth', $pthMapFile;
  26. say "Mapping to: $pthMapFile";
  27.  
  28. # Actually create mapping from file to $strMap string variable
  29. map_file my $strMap, $pthMapFile, '+<';
  30.  
  31. my $cv=AnyEvent->condvar;
  32. my $aeh=AnyEvent->timer('after'=>0, 'interval'=>1, 'cb' => sub {
  33. # Doi it immediately and repeat every 1 sec...
  34.     try {
  35.         say scalar(localtime);
  36.         @{$hsh{'t'.(int(rand 10000)+1)}}{qw/lostfunk status/} = (rand(), int(rand 25) & 1) for 7..int(rand 28)+7;
  37.         store_data(\$strMap, \%hsh);
  38.     } catch {
  39.         say "ERROR: $_";
  40.     }
  41. });
  42. $cv->recv;
  43.  
  44. sub store_data ($$$) {
  45.     my $where2store = $_[0];
  46.     my $sData = encodeByTag($_[2] // DFLT_SER_TAG() => $_[1]);
  47.     use bytes;
  48.     unless (ref $where2store) {
  49.         open my $fh, '>', $where2store;
  50.         print $fh pack('V', length $sData), $sData, "\x00" x int(length($sData)*N_PERC_RED*0.01);
  51.         close $fh;
  52.     } else {
  53.         substr(${$where2store}, 0, length($sData)+4) = pack('V', length $sData) . $sData
  54.     }
  55.     no bytes;
  56. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement