PageRenderTime 49ms CodeModel.GetById 16ms RepoModel.GetById 0ms app.codeStats 0ms

/trunk/lib/background.pl

https://github.com/jtarchie/sinatra-on-perl
Perl | 46 lines | 37 code | 5 blank | 4 comment | 5 complexity | 5cb00b91abc94169bc67afa25d6aa87c MD5 | raw file
  1. use strict;
  2. use IO::Pipe;
  3. use JSON::Any;
  4. #inter process communication
  5. my $pipe = IO::Pipe->new;
  6. sub start_job_server{
  7. return if $ENV{'SINATRA_ENVIRONMENT'} eq "TASK";
  8. my $pid = fork;
  9. if (! defined $pid) {
  10. die "Cannot start up a background process. Apparently forking is not supported.\n";
  11. } elsif($pid == 0) { #the background job server
  12. $pipe->reader;
  13. receive_job();
  14. } else { #the CGI/FCGI process
  15. $pipe->writer;
  16. $pipe->autoflush;
  17. }
  18. }
  19. #called from parent process and sends job to receiver
  20. sub send_job{
  21. my($method, @arguments) = @_;
  22. #send the dispatch to the job server
  23. my $line = JSON::Any->objToJson({
  24. 'method' => $method,
  25. 'arguments' => \@arguments
  26. });
  27. print $pipe $line . "\n";
  28. }
  29. sub receive_job{
  30. while(my $line = <$pipe>) {
  31. my $dispatch = JSON::Any->jsonToObj($line);
  32. #check to make sure this method exists
  33. my $method = $dispatch->{method};
  34. if (my $call = main->can($method)) {
  35. eval{
  36. $call->(@{$dispatch->{arguments}});
  37. };
  38. } #we don't do anything if we can't -- not are problem
  39. }
  40. }
  41. 1;