/**
 * Reads lines from a file and inputs it into a global buffer
 *
 * @param file path
 * @return NULL
 */
void *thread_read_with_mutex(void *params) {
  FILE *fp;
  char *line;
  size_t length;
  ssize_t read;
  char *file;
  t_thread_parameters *p;

  p = (t_thread_parameters *)params;
  
  file = malloc(sizeof(strlen(p->file)));
  strcpy(file, p->file);

  fp = fopen (file, "r");

  if (fp != NULL) {
    read = getline (&line, &length, fp);
    while (read > -1) {
      usleep (p->sleep_time);
      if (read > 1) {
	
	while (buff_full()) {
	  printf("fill thread: could not write -- not enough space\n");
	}
	
	printf ("fill thread: writing into buffer\n");
	sem_wait (&lock);
	buff_write (line);
	read = getline (&line, &length, fp);
	sem_post (&lock);
      }
    }
    
    while (buff_full()) {
      printf("fill thread: could not write -- not enough space\n");
    }
    sem_wait (&lock);
    printf ("fill thread: writing [QUIT] into buffer\n");
    buff_write ("QUIT");
    sem_post (&lock);
  }
  fclose (fp);
  printf("fill thread: quitting\n");
  return NULL;
}
Ejemplo n.º 2
0
int main (int argc, char **argv) {
	BUFF *bd;
	char line[20], *str;
	int num, nmax;

	if (argc == 1) nmax = NMAX;
	else nmax = atoi (*++argv);

	if (!(bd = open_buff (nmax))) {
		fprintf (stderr, "Invalid size specified\n");
		exit (1);
	}
	printf ("\n Enter a char to write," 
					" o<num> to read num no. of chars, 'exit' to exit\n");

	while (1) {
		if (buff_full(qd))
			printf ("read only: ");
		else if (buff_empty(qd))
			printf ("write only: ");
		else printf ("read/write: ");

		if (!fgets (line, 20, stdin)) exit (1);
		for (str = line; *str == ' ' || *str == '\t'; str++)
			;
		if (!strncmp(str, "exit", 4)) {
			if (!buff_empty(bd)) printf ("Remaning buffer elements : ");
			while (!buff_empty(bd))
				printf ("%c ", rd_buff(bd));
			printf ("\n===>End of App<===\n");
			exit (0);
		}

		switch (*str) {
			case '\n' : continue;
			case 'o': case 'O':
				if ((num = atoi (str + 1))) {
					while (num--) {
						if (!buff_empty(bd)) printf ("%c\n", rd_buff(bd));
						else {
							printf ("Buffer Empty\n");
							num = -1;
							break;
						}
					}
					if (num == -1) continue;
				}
			default	: 
				if (wrt_buff (bd, *str))
					printf ("Buffer Full. read out items first.\n");
				break;
		}
	}
}
/**
 * Writes string to buffer, if there is space. NULL otherwise.
 *
 * @param str character string
 * @return pointer to newly allocated string. NULL if unsuccessful
 */
void buff_write(const char *str) {
  char *new_str;
  
  if (buff_full()) {
    return;
  }

  if (str == NULL) {
    return;
  }

  #ifdef DEBUG
  printf("Allocating string of size %d\n", (int)strlen(str));fflush(stdout);
  #endif

  new_str = malloc(strlen(str) + 1);
  strcpy(new_str, str);

  gl_buff.buff[gl_buff.buff_size++] = (char *)new_str;

  #ifdef DEBUG
  printf("added string %s\n", gl_buff.buff[gl_buff.buff_size - 1]);fflush(stdout);
  #endif
}