#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>

int main(int argc, char ** argv)
{
	char kolejka[1024];
	char * getenvBuf;
	struct stat statStruct;
	char buf[1024];
	int fd;

	getenvBuf = getenv("KOLEJKA");
	if (getenvBuf != NULL)
	{
		strncpy(kolejka, getenvBuf, sizeof(getenvBuf) > sizeof(kolejka) ? sizeof(kolejka) : sizeof(getenvBuf));
	} else {
		strcpy(kolejka, "./kolejka");
	}

	printf("Plik kolejki: %s\n", kolejka);
	if (stat(kolejka, &statStruct) == -1)
	{
		snprintf(buf, sizeof(buf), "mkfifo \"%s\"", kolejka);
		system(buf);
		if (stat(kolejka, &statStruct) == -1)
		{
			printf("Nie ma pliku kolejki i nie moge go utworzyc.\n");
			exit(1);
		} else {
			printf("Utworzylem plik kolejki.\n");
		}
	}

	fd = open(kolejka, O_WRONLY);
	dup2(fd, STDOUT_FILENO);
	printf("%i:\n", getpid());
	system("date");
	return 0;
}
