/*
 *  Copyright (C) 2004 Aleksandar Colovic
 *
 *
 * This program is free software; you can redistribute it and/or modify
 * it under the terms of the GNU General Public License version 2 as
 * published by the Free Software Foundation.
 *
 */
 
#include <pthread.h>
#include <string.h>
#include <unistd.h>
#include <sys/mman.h>
#include <sys/wait.h>
#include <fcntl.h>
#include <iostream>
#include <stdint.h>
using namespace std;

int main (int argc, char* const argv[])
{
  size_t nSize = 4*1024;
  int fd = open("/tmp/pmutex", O_CREAT | O_TRUNC | O_RDWR);
  ftruncate(fd, nSize);
  void* pMem = mmap (NULL, nSize, PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
  pthread_mutex_t* pMutex = (pthread_mutex_t *)pMem;
	 
  pthread_mutexattr_t a;  
  pthread_mutexattr_init (&a);
  pthread_mutexattr_setpshared (&a, PTHREAD_PROCESS_SHARED);
  pthread_mutex_init (pMutex, &a);
  pthread_mutexattr_destroy(&a);
 
  pthread_mutex_lock(pMutex);
  cout << "Process 1 locked the mutex ..." << endl;
 
  pid_t nChildPid = fork();
  if (0 == nChildPid) 
  {
	execvp("./process2", 0);
	exit(1);
  }
	
  sleep (5);
  pthread_mutex_unlock(pMutex);
  cout << "Process 1 released the mutex!" << endl;
  waitpid(nChildPid, 0, 0);
  cout << "Process 1 exiting ..." << endl;
  close(fd);
  return 0;
}

