// Jarosław Ogrodnik ID3 Indeks: 1234
#include <stdio.h>
#include <unistd.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/msg.h>
#include <sys/stat.h>
#include <fcntl.h>

#define BLAD     "BLAD\n"
#define	MY_FIFO "./plik_fifo"
#define LEN 256

char buf2[256];
int f,g;
char x[256];
int y;
int z;

int main()
{
        int fifo,dlugosc=256;
	char buf[LEN];

	// Sprawdzenie dostepnosci i usuniecie kolejki
	   if (access(MY_FIFO,F_OK) != -1) 
	   {
	     if (unlink(MY_FIFO) < 0) 
	     {
	           write(STDERR_FILENO,BLAD,strlen(BLAD));
	                 return 1; 
	     }
	   }
	

	// Utworzenie kolejki            
    if (mknod(MY_FIFO,S_IFIFO|0666,0) < 0) 
    {	         
	    write(STDERR_FILENO,BLAD,strlen(BLAD));
	    return 1; 
    }

    
    if ((f=fork()) == -1)
    {
             write(STDERR_FILENO,BLAD,strlen(BLAD));
             return(1);
    }
    

  else

    if (f== 0)
    {
do
      {
         // Kod procesu potomnego1
	
	// Otwarcie kolejki do zapisu      
	    if ((fifo=open(MY_FIFO,O_WRONLY)) < 0) 
	    {
	    	write(STDERR_FILENO,BLAD,strlen(BLAD));
	    		return 1; 
	    }  

        printf("Wprowadz tekst: ");
        fgets(x,256,stdin);
        x[strlen(x)-1]='\0';
        y=getpid();
        printf("Wyprowadzenie na stdout zawartosci wysylanej kolejki (z potomka1):\n ");
        sprintf(buf,"Ogrodnik, %s, %d",x,y);
        fputs(buf,stdout);

        printf("\n");

	// Pisanie do kolejki  
	 if ((dlugosc=write(fifo,buf,LEN)) < 0) 
	{
	 	write(STDERR_FILENO,BLAD,strlen(BLAD));
	 	return 1; 
	}; 

        sleep(2);
        } while(1);
        return(1);
    }

  
    if ((g=fork())== -1)
    {
	    write(STDERR_FILENO,BLAD,strlen(BLAD));
	    	return 1; 
    }
    

    if (g==0)
    {
        // Kod procesu potomnego2
        do
        {

	
		 // Otwarcie kolejki do odczytu      
	if ((fifo=open(MY_FIFO,O_RDONLY)) < 0) 
	{
		write(STDERR_FILENO,BLAD,strlen(BLAD));
		return 1; 
	}
		 
	// Czytanie z kolejki
	 if ((dlugosc=read(fifo,&buf,LEN)) < 0)
	 {
	 	write(STDERR_FILENO,BLAD,strlen(BLAD));
	 	return 1; 
	 }; 

        z=getpid();
        sprintf(buf2,"%s, %d\n",&buf,z);

        printf("Wyprowadzenie na stdout odczytanej kolejki z PID procesu potomnego2:\n ");
        fputs(buf2,stdout);
	sleep(2);	
        } while(1);
       return(1);
//	while (1)
//	{
//	};
    }
    else
	    while(1){
	    }
}


