#!/usr/bin/perl
use strict;
use warnings;

use WWW::Curl::Easy;
use WWW::Curl::Multi;


pipe(my $libcurl, my $daemon)|| die $!;

unless (my $libcurlpid = fork) {
    # Child -- libcurl thread
    close $daemon;

    my %easy;
    my $curlm = WWW::Curl::Multi->new;
    my $curl_id = $$; # This should be a handle unique id.
    my $active_handles = 0;

    # Loop requests
    while (<$libcurl>) {
	print "Got request $_\n";
	my $curl = new WWW::Curl::Easy;
	$easy{$curl_id} = $curl; # Register handle
	$curl->setopt(CURLOPT_PRIVATE,$curl_id); # Assign Multi ID
	# do the usual configuration on the handle

	$curl->setopt(CURLOPT_VERBOSE, 1);
	$curl->setopt(CURLOPT_DNS_CACHE_TIMEOUT, -1);
	$curl->setopt(CURLOPT_NOBODY, 1);

	$curl->setopt(CURLOPT_URL, $_);

	# Add easy handles to multi
	$curlm->add_handle($curl);
	$active_handles++;

	while (my $active_transfers = $curlm->perform) {
	    if ($active_transfers != $active_handles) {
		while (my ($id,$return_value) = $curlm->info_read) {
		    if ($id) {
			$active_handles--;
			my $actual_easy_handle = $easy{$id};
			# do the usual result/error checking routine here
			#	    ...
			# letting the curl handle get garbage collected, or we leak memory.
			delete $easy{$id};
		    }
		}
	    }
        }
    }
    exit;
}

close $libcurl;
if (my $pid = fork) {
    &doloop;
}
else {
    &doloop;
}

sub doloop
  {
      my $n=4;
     while ($n--) {
	  print "$$: Sending request\n";
	  print $daemon "http://ftp.us.debian.org\n";
     }
  }


