Esempio n. 1
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;
		}
	}
}
/**
 * Stores string from top of global buffer into a given file
 *
 * @param file path
 * @return NULL
 */
void *thread_write_with_mutex (void *params) {
  FILE *fp;
  char *str;
  char *file;
  t_thread_parameters *p;

  p = (t_thread_parameters *)params;
  file = malloc(sizeof(strlen(p->file)));
  strcpy(file, p->file);
  fp = fopen (file, "w+");
  if (fp != NULL) {
    while ((gl_buff.quit_flag == 0) || (!buff_empty())) {
      usleep (p->sleep_time);
      while (buff_empty()) {
	printf ("drain thread: no new strings in buffer\n");
      }
      
      sem_wait (&lock);
      str = buff_read();
      
      if ((strcmp (str, "QUIT")) == 0) {
	printf ("drain thread: read [QUIT] from buffer\n");
	gl_buff.quit_flag = 1;
      }
      else {
	printf ("drain thread: read from buffer\n");
	#ifdef DEBUG
	printf ("read '%s' size of %d\n", str, (int) strlen(str));
	#endif
	fwrite (str, 1, strlen(str), fp);
      }
    
      sem_post (&lock);
    }
  }
 
  fclose (fp);
  
  printf ("drain thread: quitting\n");
  return NULL;
}
/**
 * Reads most recently inserted string. Decrements counter
 *
 * @return pointer to newly allocated string. NULL if unsuccessful
 */
char *buff_read() {
  char *str;

  if (buff_empty()) {
    return NULL;
  }

  str = gl_buff.buff[--gl_buff.buff_size];

  #ifdef DEBUG
  printf("STRING %s\n", str);
  #endif

  return str;
}