+ if ($@ || $main::is_win) {
+# print STDERR "POSIX Blocking *** NOT *** supported $@\n";
+ $blocking_supported = 0;
+ } else {
+ $blocking_supported = 1;
+# print STDERR "POSIX Blocking enabled\n";
+ }
+
+
+ # import as many of these errno values as are available
+ eval {
+ require Errno; Errno->import(qw(EAGAIN EINPROGRESS EWOULDBLOCK));
+ };
+}
+
+my $w = $^W;
+$^W = 0;
+my $eagain = eval {EAGAIN()};
+my $einprogress = eval {EINPROGRESS()};
+my $ewouldblock = eval {EWOULDBLOCK()};
+$^W = $w;
+$cnum = 0;
+
+
+#
+#-----------------------------------------------------------------
+# Generalised initializer
+
+sub new
+{
+ my ($pkg, $rproc) = @_;
+ my $obj = ref($pkg);
+ my $class = $obj || $pkg;
+
+ my $conn = {
+ rproc => $rproc,
+ inqueue => [],
+ outqueue => [],
+ state => 0,
+ lineend => "\r\n",
+ csort => 'telnet',
+ timeval => 60,
+ blocking => 0,
+ cnum => (($cnum < 999) ? (++$cnum) : ($cnum = 1)),
+ };
+
+ $noconns++;
+
+ dbg("Connection created ($noconns)") if isdbg('connll');
+ return bless $conn, $class;
+}
+
+sub set_error
+{
+ my $conn = shift;
+ my $callback = shift;
+ $conn->{eproc} = $callback;
+ set_event_handler($conn->{sock}, error => $callback) if exists $conn->{sock};
+}
+
+sub set_rproc
+{
+ my $conn = shift;
+ my $callback = shift;
+ $conn->{rproc} = $callback;
+}
+
+sub blocking
+{
+ return unless $blocking_supported;
+
+ my $flags = fcntl ($_[0], F_GETFL, 0);
+ if ($_[1]) {
+ $flags &= ~O_NONBLOCK;
+ } else {
+ $flags |= O_NONBLOCK;
+ }
+ fcntl ($_[0], F_SETFL, $flags);
+}
+
+# save it
+sub conns
+{
+ my $pkg = shift;
+ my $call = shift;
+ my $ref;
+
+ if (ref $pkg) {
+ $call = $pkg->{call} unless $call;
+ return undef unless $call;
+ dbg("changing $pkg->{call} to $call") if isdbg('connll') && exists $pkg->{call} && $call ne $pkg->{call};
+ delete $conns{$pkg->{call}} if exists $pkg->{call} && exists $conns{$pkg->{call}} && $pkg->{call} ne $call;
+ $pkg->{call} = $call;
+ $ref = $conns{$call} = $pkg;
+ dbg("Connection $pkg->{cnum} $call stored") if isdbg('connll');
+ } else {
+ $ref = $conns{$call};
+ }
+ return $ref;
+}
+
+# this is only called by any dependent processes going away unexpectedly
+sub pid_gone
+{
+ my ($pkg, $pid) = @_;
+
+ my @pid = grep {$_->{pid} == $pid} values %conns;
+ foreach my $p (@pid) {
+ &{$p->{eproc}}($p, "$pid has gorn") if exists $p->{eproc};
+ $p->disconnect;
+ }