How to set up fork correctly in perl module for znc?
I am currently writing an IRC bot. The scripts are loaded as perl modules in ZNC , but the bot crashes with an I / O error if I create a forked process. This is a working example script without a fork, but it causes the bot to freeze until the script finishes executing its task.
package imdb;
use warnings;
use strict;
sub new
{
my ($class) = @_;
my $self = {};
bless( $self, $class );
return( $self );
}
sub OnChanMsg
{
my ($self, $nick, $channel,$text) = @_;
#unless (my $pid = fork()) {
my $result = a_slow_process($text);
ZNC::PutIRC( "PRIVMSG $channel :$result" );
# exit;
#}
return( ZNC::CONTINUE );
}
sub OnShutdown
{
my ( $me ) = @_;
}
sub a_slow_process {
my $input = shift;
sleep 10;
return "You said $input.";
}
1;
The fork code causing the error has been commented out. How to fix it?
Edited to add : I was told that ZNC :: PutIRC should not be put in a child process.
a source to share
A fork()
call affects open file and socket descriptors, including:
File descriptors (and sometimes these descriptors are locked) are split and everything else is copied.
...
Since v5.6.0, Perl will try to flush all files open for output before forking the child process, but this may not be supported on some platforms (see perlport). You may need to install $ | ($ AUTOFLUSH in English) or call the "autoflush ()" IO :: Handle method on any open handles to avoid duplicate output.
and it is generally not recommended to establish a socket connection in one process and try to read / write that connection in a child process.
A workaround might be to create a new ZNC connection in the child process (after execution a_slow_process()
), write a private message and close the new connection.
a source to share