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

/* Just fork(), but don't exec(). */
/* Pass the value as a command line argument. */

int main(int argc, char *argv[])
{
  pid_t pid;
  unsigned long n;
  char arg[20];
  int stat;

  n = atoi(argv[1]);
  printf("factorial: %ld\n", n);

loop:
  if (n == 0) {
    printf("return 1 (%d)\n", (int)getpid());
    return 1;
  }
 
  if ((pid = fork()) < 0) {
    perror("fork");
    exit(1);
  }
  else if (pid == 0) {
    /* child */
    n--;
    goto loop;
  }
  else {
    /* parent */
    waitpid(pid, &stat, 0);
    stat = WEXITSTATUS(stat);
    printf("pid = %d; stat = %d\n", (int)pid, stat);
  }
  printf("return %d\n", n * stat);
  return (n * stat);
}
