#!/usr/bin/perl

use strict;
use warnings;


use BerkeleyDB;

our $cfg;
my $count=2;

sub sig_handler {
    warn "Got SIG@_. Exiting gracefully!\n" if $cfg->{debug};
    exit 1;
}

sub db {
    for ('INT', 'TERM', 'PIPE', 'QUIT', 'HUP', 'SEGV') {
	$SIG{$_} = \&sig_handler unless $SIG{$_};
    }

    my $env = new BerkeleyDB::Env
      -Home   => '/tmp',
	-Flags => DB_CREATE | DB_INIT_MPOOL | DB_INIT_CDB,
	  -ErrFile => *STDERR,
	    -ThreadCount => 64,
	      -ErrPrefix => "[$$]:"
		or die $BerkeleyDB::Error;

    $env->set_isalive();
    if ($env->failchk == DB_RUNRECOVERY) {
	warn "Failed thread detected.\n";
    }

    $SIG{ALRM} = sub {
	$env->failchk;
	alarm 1;
    };
    alarm 1;

    my $dbh = new BerkeleyDB::Btree
      -Filename => '/tmp/test.db',
	-Flags => DB_CREATE,
	  -Env => $env
	    or die $BerkeleyDB::Error;
    undef $env;
    return $dbh;
}

sub fetch_store {
    my $cpid;
    my $dbh=db();
    warn "[$$]: Init DB in fetch_store\n";

    $dbh->db_put('test', 0) && die $!;
    $dbh->db_get('child', $cpid) && die $!;
    return 1;
}


sub return_file {
	    my $dbh=$_[0];
	    warn "[$$]: Init DB in return_file\n";
	    $dbh->db_put('child', $$) && die $!;
	    return 1;
}

while ($count--) {
    my $pid = fork;
    die $! unless defined $pid;
    if ($pid == 0) {
	fetch_store();
	exit(0);
    }
    # use %db here
    warn "[$$]: Child fetcher process $pid\n";
    if (return_file(db())) {
	sleep 1;
    }
}
