#include <arpbase.h>
#include <arp_proto.h>
#include "Launch.h"
#include "LaunchPriv.h"


/*
 *	NAME
 *		WaitProcesses -- wait for all child processes to end.
 *
 *	SYNOPSIS
 *		WaitProcesses ()
 *
 *		void WaitProcesses (void);
 *
 *	FUNCTION
 *		Wait until all processes that were launched by this process
 *		are finished.  You MUST call this at the end of your program
 *		since it also cleans up some memory allocation when there are
 *		no more child.
 *
 *	DESCRIPTION
 *		Scan the process pair list and for each process that we are
 *		the parent of we wait until it ends and we remove the process
 *		pair and free the memory.
 *
 *		When all process pair have been scanned, we free the parent's
 *		signal bit and try to free the list.
 *
 *		The fact that we wait while we scan the list does not matter
 *		since the list cannot go away (it contain at least one pair,
 *		ours) and the next pointer is only used AFTER we return from
 *		the wait.
 *
 *	INPUT
 *		None.
 *
 *	OUTPUT
 *		None.
 *
 *	HISTORY
 *		1992/09/06	Pierre Baillargeon		Creation
 *		1992/09/07	Pierre Baillargeon		Update
 *					Made faster and simpler.
 *
 *	SEE ALSO
 *		WaitProcess(), WaitProcFunc()
 */

void WaitProcesses (void)
{
	struct ProcPair *pp, *ppn;
	struct Process *Proc;
	LONG Bit;

	Bit = -1L;
	Proc = (struct Process *)FindTask (NULL);

	Forbid ();
	for (pp = (struct ProcPair *)ProcPairList->lh_Head; pp->pp_Node.ln_Succ; pp = ppn)
	{
		if (Proc == pp->pp_Parent)
		{
			Bit = pp->pp_ParentBit;
			while (pp->pp_ChildEntry)
			{
				Wait (1L << Bit | KILL_PROCESS_FLAG);
			}
			ppn = (struct ProcPair *)pp->pp_Node.ln_Succ;
			Remove (&pp->pp_Node);
			FreeMem (pp, sizeof (struct ProcPair));
		}
		else
		{
			ppn = (struct ProcPair *)pp->pp_Node.ln_Succ;
		}
	}

	FreeParentSignal (Bit);
	FreeProcPairList ();
	Permit ();
}
