// Department of Computing, Imperial College London
// Operating Systems Concepts 
// Olav Beckmann, with acknowledgements to Paul Kelly
// Tutorial 3 - process_create.c
// 

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

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

  printf( "How many processes would you like to create?\n" );
  scanf( "%d", &numprocs );
  printf( "Number of child processes that will be created: %d.\n", numprocs );

  for( i = 0; i < numprocs; ++i ) {
    int pid = fork();
    if( pid < 0 ) {
      fprintf( stderr, "Could not create a new process.\n" );
      exit( -1 );
    }
    else if( pid == 0 ) {
      execlp( "xcalc", "xcalc", NULL );
      /* This is the child process */
    }
    else { 
      /* This is the parent process */ 
      printf( "PID of the child process that has been created: %d.\n", pid ); 
    }
  }

  for( i = 0; i < numprocs; ++i ) {
    int pid = wait( &status );
    printf( "pid of process that just exited: %d.\n", pid );
  }

  return 0;
}

