How to exit a program running under a Morbo or Hypnotoad server

584 Views Asked by At

In the programs running under the Morbo (and Hypnotoad) server a call of exit() is silently ignored and effectively works as a return from the callback. An END block fires as usually but a program itself never exits.

#!/usr/bin/perl

use Modern::Perl;
use Mojolicious::Lite;

END {
  say "END block";
}

 Mojo::IOLoop->timer(5 => sub {
  say "Sleeping...";
  sleep 15;
  say "Before...";
  exit(1);
  say "Never seen";
});

app->start;   

$ morbo test.pl
Server available at http://127.0.0.1:3000
Sleeping...
Before...
END block
^C 
2

There are 2 best solutions below

0
On

When starting a Mojolicious-app something bad could happen (no database-connection). I decided to change the root-URL of my app.

In Myapp.pm:

sub startup {
    my $app = shift;
    $app->plugin('Config');
    ...
    my $r = $app->routes;
    $r->get('/')->to('root#index')->name('root');

    eval {
        $app->check_important_things_which_can_die;
    };
    if ($@) {
       $r->find('root')->remove;
       $r->get('/')->to('Error::Root#index')->name('error_root');
    }

I don't know wether this works in a running application after routing has been used.

0
On

You can issue a kill to the parent process ID from within your Handler:

system "kill -s INT " . getppid();

This will gracefully exit the server process, killing any workers that have been launched. Also works for Hypnotoad.