/* forkmt.c (emx+gcc) */

/* Check inheritance of _rmutex semaphores. */

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <sys/builtin.h>
#include <sys/fmutex.h>
#include <sys/rmutex.h>

static _rmutex rm;


static void thread (void *arg)
{
  /* This is a dirty test program -- the semaphore is not owned by
     this thread.  Do not do this in application programs. */

  _rmutex_checked_release (&rm);
}


static void test (char c)
{
  char *p;

  write (1, &c, 1);
  p = malloc (1000);
  if (p == NULL)
    abort ();
  _rmutex_checked_request (&rm, _FMR_IGNINT);
  if (_beginthread (thread, NULL, 0x8000, NULL) == -1)
    abort ();
  _rmutex_checked_request (&rm, _FMR_IGNINT);
  c += 'a' - 'A';
  _rmutex_checked_release (&rm);
  write (1, &c, 1);
}


int main (void)
{
  int pid;

  if (_osmode != OS2_MODE)
    {
      puts ("This program requires OS/2.");
      return 0;                 /* Don't abort regression test */
    }
  puts ("This program should print the letters AaBbCcDd, where A must come\n"
        "before a, B must come before b, and so on.  For instance, the\n"
        "output AaCBcbEDed is acceptable.\n");

  _rmutex_checked_create (&rm, 0);
  test ('A');
  pid = fork ();
  if (pid != 0)
    {
      test ('B');
      waitpid (pid, NULL, 0);
    }
  else
    {
      test ('C');
      pid = fork ();
      if (pid != 0)
        {
          test ('D');
          waitpid (pid, NULL, 0);
        }
      else
        test ('E');
    }
  return 0;
}
