/*-----------COMMUTATION DE MESSAGE-------------------
Pere qui est a la fois Emetteur et Recepteur du message);message recuper au clavier
Pas de circuit virtuel :chacun  des commutateur decide aleatoirement a qui il envoie le message
                  IUP GMI 
----------Presentation Koffi FOLIKPO-AWUTE-----------*/

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include<sys/time.h>
#include<string.h>
#include<sys/wait.h>
#include <errno.h>

char msg[26];
int p[3][2];
struct timeval rtemps;
fd_set rfds, wfds;

void ActionFils(int, int);
int main(void)
{
  int i, retval;
  int pid[3],j,k,n, val=0;
  char msgI[26];
  pid_t  pidPere=getpid();
  pid_t  pidFils;
  srand(time(NULL));
  rtemps.tv_sec = 2;
  rtemps.tv_usec= 0;

  for(i=0;i<3;i++)
{
      if(pipe(p[i])<0)
    {
        perror("pipe mal utilise");
        exit(1);
    }
      printf("Tube_Lecture: %d\n",p[i][0]);
      printf("Tube_Ecriture: %d\n",p[i][1]);
      FD_SET(p[i][0],&rfds);
      FD_SET(p[i][1],&wfds);
}

  printf("Etrez le message envoyer par le pere\n");
  scanf("%s",&msgI);

  write(p[i=rand()%3][1], &msgI, sizeof(msgI));
  printf("je suis le Pere %d : Envoie de message initial: %s\n",getpid(),msgI);

  for(k=0;k<2;k++)
    {
      j=rand()%2;
      pid[j]=fork();/* creation de process fils */
      switch(pid[j])
        {
        case -1 :/* erreur */
          perror("erreur fork()");
          break;
        case 0 :/* process fils */
          printf("je suis le fils %d, ",getpid());
          {
            retval=select(9, &rfds, &wfds,NULL, &rtemps);
            if(retval)
              {
                for(i=0;i<3;i++)
                  {
                  for(n=0; n<3; n++)
                    {
                      if(FD_ISSET(p[i][0],&rfds)||FD_ISSET(p[n][1],&wfds))
                        {
                          if(j==0)
                          ActionFils(i,n);
                          else if(j==1)
                          ActionFils(i, n);
                        }
                    }
                  }
              }
          }
        default :/*process pere*/
          break;
        }
  }

  if(pidPere==getpid())
    {

        retval=select(9, &rfds, NULL, NULL, &rtemps);
        if(retval)
          {
            for(i=0;i<6;i++)
              {
                if(FD_ISSET(p[i][0],&rfds))
          {
                    read(p[i][0], &msg, sizeof(msg));
                    printf("Moi le pere %d    ,je recois en retour: %s\n",getpid(),msg);
                  }
              }
          }
    }
  pidFils=wait(&val);
  return 0;
}
/*Fonction qui fait l'action de lecture et d'ecriture
  par les fils*/

void ActionFils(int r, int w)
{
  read(p[r][0], &msg, sizeof(msg));
  printf("\nj'ai recu le message: %s\n",msg);
  write(p[w][1], &msg, sizeof(msg));
  exit(1);
}
