Using

Scripting

Perl Pseudo Threads

  1. use strict;
  2. use warnings;
  3. use File::Spec;
  4. use Xchat qw(:all);
  5.  
  6. hook_command("pseudothread", \&cmd_hook);
  7.  
  8. my $tutorial_path = File::Spec->catdir(get_info('xchatdirfs'),'tutorial');
  9. my $pseudothread_script = File::Spec->catdir($tutorial_path, 'pseudothread-fork.pl');
  10. my $timer;
  11.  
  12. sub cmd_hook {
  13.         my $result_file = 'pseudothread.completed';
  14.         system ('perl', $pseudothread_script, $tutorial_path, $result_file, (defined $_[1][1] ? $_[1][1] : ()));
  15.         $timer = hook_timer(1000, \&pseudo_thread_timer, {data=>File::Spec->catdir($tutorial_path, $result_file)});
  16.         return EAT_XCHAT;
  17. }
  18.  
  19. sub pseudo_thread_timer {
  20.         my $check_file = $_[0];
  21.         if (!-e $check_file) {
  22.                 prnt ("$check_file Does Not Exist");
  23.                 return KEEP;
  24.         }
  25.         else {
  26.                 prnt ("$check_file Does Exist");
  27.                 # read the contents and display
  28.                 open (RESULT, '<', $check_file);
  29.                 while (<RESULT>) {
  30.                         prnt $_;
  31.                 }
  32.                 close RESULT;
  33.                 # now delete it, so it can be called again
  34.                 unlink $check_file;
  35.                 return REMOVE;
  36.         }
  37. }
tutorial/pseudothread-fork.pl
  1. use strict;
  2. use warnings;
  3. use File::Spec;
  4.  
  5. my $resultfile = File::Spec->catdir($ARGV[0], $ARGV[1]);
  6.  
  7. # in our method of tracking the thread completion, we must be able to write to the out file
  8. # but it cannot exist before hand, since it is deleted after it is read
  9. if (-d $ARGV[0] && -w $ARGV[0] && !-e $resultfile) {
  10.         # standard fork behavior to follow!
  11.         my $pid = fork;
  12.  
  13.         # here is where the "thread" goes, with all forks, the $pid at this point is set to 0
  14.         if ($pid == 0) {
  15.                 # the sleep is just an example to show the non blocking nature of this method
  16.                 sleep (3);
  17.                 # Attempt to open for writing, it is -w, so it SHOULD, but can't be to safe0
  18.                 if (open (RESULT, '>', $resultfile)) {
  19.                         print RESULT (defined $ARGV[2] ? $ARGV[2] : "George!");
  20.                         close RESULT; # close that file handle!
  21.                 }
  22.         }
  23.  
  24. }
  25.  
  26. # all done, either the parent will continue at the point of the system call, or the fork process will just terminate


Print - Recent Changes - Search
Page last modified on February 06, 2010, at 01:25 PM