#include "pvm3.h"
#include <stdio.h>
#include <unistd.h>
#include <stdlib.h>
#define nproc 2

int main(int argc, char **argv)
{
   int tid;
   int parent_id;
   int *tids;
   int tid_recv;
   int c;
   int i;
   char hname[128];

   tid = pvm_mytid();
   parent_id = pvm_parent();

   if ( parent_id  <  0 ) 
   {
      tids = (int *) malloc(nproc * sizeof(int));

      c = pvm_spawn(argv[0],  (char **) NULL,  PvmTaskDefault,
         NULL , nproc, tids);
      if (c != nproc)
      {
         fprintf(stderr, "Failed to spawn %d processes\n",  nproc);
         pvm_exit();
         exit(1);
      }
      #ifdef DEBUG
         for(i=0; i<nproc; i++)
         {
            printf("task id %00x\n", tids[i]);
         }
      #endif
      free (tids);
   }
   pvm_joingroup ("nodes");

   if (parent_id  <  0)
   {
      for ( i = 0 ;  i < nproc;  i++ )
      {
         pvm_recv(-1,  -1);
         pvm_upkint(&tid_recv, 1, 1);
         pvm_upkstr(hname);
         printf("Hello world from tid %00x running on %s\n", tid_recv, hname);
      }
   }
   else
   {
      gethostname(hname, 128);

      pvm_initsend(PvmDataDefault);
      pvm_pkint(&tid, 1, 1);
      pvm_pkstr(hname);
      pvm_send(parent_id, 0);
   }
   pvm_barrier("nodes",  nproc + 1);
   pvm_exit();
   return 0;
}
