#include <pthread.h>
#include <stdio.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>

/*
 * Programa simples para exemplo de criacao de threads
 *
 * Jose Rogado
 *
 */

int file;

main(int argc, char *argv[])
{
   int func1(int );
   int func2(int );
   int ret;
   char buffer[64];
   pthread_t thread1, thread2;
   pthread_attr_t attr;

   file = open (argv[1], O_RDWR);
   if (file < 0) {
     perror("file");
     exit(1);
   }
   printf("Main thread\n");

   ret = pthread_create(&thread1, NULL, (void *)(&func1), (void *)1);
   if (ret)
     {
	printf("ret %d\n", ret);
	perror("thread create");
	exit(1);
     }

   ret = pthread_create(&thread2, NULL, (void *)(&func2), (void *)2);
   if (ret)
     {
	printf("ret %d\n", ret);
	perror("thread create");
	exit(1);
     }

   pthread_join(thread1, NULL);
   pthread_join(thread2, NULL);

   printf("All Joined\n");
   
 // Reset the file I/O pointer to begin of file !!
   lseek(file, 0, SEEK_SET);

   ret = read(file, buffer, sizeof(buffer));
   if (ret < 0) {
     perror("read");
     exit(1);
   }
   printf("File content: %s ", buffer);
   printf("%s\n", buffer+strlen(buffer)+1);
}


func1(int i)
{
  int ret;
  const char msg[] = "Hello1";

  printf("Thread1: %s %d\n", msg, i);
  ret = write(file, msg, sizeof(msg));
  if (ret < 0)
     perror("write");
}

func2(int i)
{
  int ret;
  const char msg[] = "Hello2";

  printf("Thread2: %s %d\n", msg, i);
  ret = write(file, msg, sizeof(msg));
  if (ret < 0)
     perror("write");
}
