#include <stdio.h>
#include <unistd.h>
#include <memory.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <signal.h>

#define MAX 65535 /* mind, (short) -1 == (ushort) 65535 */

static pid_t pids[MAX];

void
testing( int real )
{
  int   i, status;
  pid_t pid;

  for ( i=0; i<MAX; i++ ) {
    if ( (pid=pids[i]=fork()) == -1 ) {
      if ( errno != EAGAIN && errno != ENOMEM ) perror( "\ncannot fork" );
      break;
    } else if ( pid==0 ) {
      if ( real ) sleep(86400); /* one day */
      exit(i & 127);
    }
    if ( (i & 15) == 0 ) printf( "\rspawned child #%d", i );
  }

  printf( "\nYou can have %d %s processes.\n", i, real ? "real" : "virtual" );
  for ( i--; i>=0; i-- ) {
    if ( real ) kill( pids[i], SIGTERM ); 
    waitpid( pids[i], &status, 0 );
    if ( (i & 15) == 0 ) printf( "\rkilled child #%d", i );
  }

  printf( "\r                  \r" );
}

int
main( int argc, char* argv[] )
{
  int   i, status;
  pid_t pid;

  memset( pids, 0, sizeof(pids) );
  setbuf( stdout, 0 );

  testing( 0 );
  testing( 1 );

  return 0;
}

