/*
 * NAME
 *   Dispatch.c
 * USAGE
 *   Dispatch ProgramName [Argument,...]
 * DESCRIPTION
 *   Run a number of children executing ProgramName concurrently, starting a
 *   new child when a child terminates normally. Dispatch terminates when an
 *   error occurs, or when all of it's children have terminated normally. The
 *   maximum number of concurrent children is determined by the environment 
 *   variable SKIMPROCESSES. When this variable is not set, the default is 4. 
 *   Every argument in the list is provided to exactly one process as it's 
 *   first argument. Thus the number of arguments in the list determines the 
 *   total number of children run by the dispatcher. The program ProgramName is
 *   located using the search path specified by the PATH environment variable.
 *
 *   In genealogical terms, Dispatch runs a family where a new child is born
 *   when an older child leaves the house. Every child is born with exactly
 *   one mission. The maximum number of children in the house, the total number
 *   of children in the family and the mission of every child are predetermined 
 *   when Dispatch starts the family.
 * EXAMPLE
 *   When SKIMPROCESSES defaults to 4, the command:
 *
 *       Dispatch sleep 1 2 3 4 5 6 7 8
 *
 *   spawns the commands 'sleep 1', 'sleep 2' ..., 'sleep 8', running a
 *   maximum of 4 sleep processes concurrently. It terminates after 12 seconds.
 * COPYRIGHT
 *   Skim - Off-line news reading package optimized for slow lines.
 *   Copyright (C) 1995  Rene W.J. Pijlman
 *
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation; either version 2 of the License, or
 *   (at your option) any later version.
 *
 *   This program is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this program; if not, write to the Free Software
 *   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.
 * VERSION
 *   Skim version 0.6.
 */

#include <stdio.h>
#include <stdlib.h>
#include <limits.h>
#include <assert.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

#include "Skim.h"

FILE_ID("/home/rene/sys/CVS_MasterSourceRepository/skim/Dispatch.c,v 1.6 1995/08/15 19:33:33 rpijlman Exp");

#define USAGE "Usage: Dispatch ProgramName [Argument,...]"
#define ARGC_PROGRAM_NAME   1
#define ARGC_FIRST_ARGUMENT 2

#define DEFAULT_MAXIMUM_NUMBER_OF_CHILDREN 4

static void WaitForAChild( const char * ProgramName )
{
    int Status;

    if ( wait( &Status ) <= 0 )
    {
	perror( "wait" );
	exit( EXIT_FAILURE );
    }

    if ( !WIFEXITED( Status ) )
    {
	fprintf( stderr, "An instance of %s failed.\n", ProgramName );
	exit( EXIT_FAILURE );
    }
}

int main( int argc, char ** argv )
{
    int CurrentNumberOfChildren = 0;
    int MaximumNumberOfChildren;
    int Status;
    char * p;
    int i;

    if ( argc < 2 )
    {
        fprintf( stderr, "%s\n", USAGE );
        exit( EXIT_FAILURE );
    }

    if ( ( p = getenv( "SKIMPROCESSES" ) ) != NULL )
    {
        MaximumNumberOfChildren = atoi( p );

        /* CHILD_MAX is a Linux limit defined in /usr/include/linux/limits.h. */
	if ( MaximumNumberOfChildren < 1 ||
	     MaximumNumberOfChildren > CHILD_MAX )
	{
	    fprintf( stderr, "%s\n",
	             "Invalid value for environment variable SKIMPROCESSES" );
	    exit( EXIT_FAILURE );
	}
    }
    else
    {
        MaximumNumberOfChildren = DEFAULT_MAXIMUM_NUMBER_OF_CHILDREN;
        assert( MaximumNumberOfChildren <= CHILD_MAX );
    }

    for ( i = ARGC_FIRST_ARGUMENT; i < argc; i++ )
    {
        if ( CurrentNumberOfChildren >= MaximumNumberOfChildren )
        {
            WaitForAChild( argv[ ARGC_PROGRAM_NAME ] );
            CurrentNumberOfChildren--;
        }

        /* Start a new child in the background. */
        Status = fork();
        if ( Status == 0 )
        {
            /* In the child. */
            Status = execlp( argv[ ARGC_PROGRAM_NAME ], 
                             argv[ ARGC_PROGRAM_NAME ],
                             argv[ i ], NULL );
	    if ( Status < 0 )
	    {
	        perror( "execlp" );
	        exit( EXIT_FAILURE );
	    }
        }
        else if ( Status > 0 )
        {
            /* In the parent. */
            CurrentNumberOfChildren++;
        }
        else 
        {
            /* In the wannabee-parent. */
            perror( "fork" );
            exit( EXIT_FAILURE );
        }
    }

    /* Wait for all remaining children to terminate. */
    for ( i = 0; i < CurrentNumberOfChildren; i++ )
    {
	WaitForAChild( argv[ ARGC_PROGRAM_NAME ] );
    }

    return EXIT_SUCCESS;
}
