void			obj_delete_data(t_obj_data **d)
{
	t_obj_data	*data;

	data = *d;
	lst_destroy(&data->positions, free);
	lst_destroy(&data->uvs, free);
	lst_destroy(&data->normals, free);
	lst_destroy(&data->polygons, delete_polygons);
	free(data);
	*d = NULL;
}
Exemple #2
0
/* Destroy shared resources */
void destroySharedResources() {
  lst_destroy(g_lst_children);
  
  mutex_destroy(&g_mutex);
  
  cond_destroy(&g_child_cv);
  cond_destroy(&g_monitoring_cv);
}
static void
_destroy_linkage_block_ (_linkage_block_ *linkage_block)
{
  assert (linkage_block);

  lst_destroy (linkage_block -> candidate_line_lst);
  free (linkage_block);
}
Exemple #4
0
int main(int argc, char *argv[])
{
	list_t *pilha;
	
	while(1){
		/* initialize the stack */
		pilha = lst_new();

		/* integration and data processing */
		leOperacao(pilha);

		/*free memory of the stack*/
		lst_destroy(pilha);
	}

	return 0;
}
/*===================================================
=		Função que destroi todas as variáveis		=
=			e estruturas da par-shell            	=
===================================================*/
void destroy_variables(){
	/**
	 * 	Destruir mutex e variáveis de condição
	 */
	if(pthread_mutex_destroy(&mutex) < 0){
		perror("Erro no pthread_mutex_destroy: ");
		exit(EXIT_FAILURE);
	}
	if(pthread_cond_destroy(&podeCriarFilhos) < 0){
		perror("Erro no pthread_cond_destroy do podeCriarFilhos: ");
		exit(EXIT_FAILURE);		
	}
	if(pthread_cond_destroy(&podeMonitorizar) < 0){
		perror("Erro no pthread_cond_destroy do podeMonitorizar: ");
		exit(EXIT_FAILURE);
	}
	/**
	 * 	Destruir listas
	 */
	lst_destroy(list);
	terminais_destroy(lista_terminais);
	/**
	 * 	Fechar ficheiro log e ligação com o pipe
	 */
	if(fclose(ficheiro_log) == EOF){
		perror("Erro no fclose do destroy_variables: ");
	}
	if(close(inputdesc) < 0){
		perror("Erro no close do destroy_variables: ");
	}
	if(unlink(inputpipe) < 0){
		if (errno != ENOENT) {
			perror("Erro no unlink do destroy_variables: ");
			exit(EXIT_FAILURE);
		}
	}
}
int main(int argc, char **argv){
	char buffer[BUFFER_SIZE];
	int numArgs;
	char *arg_vector[VECTOR_SIZE];
	time_t starttime;
	
	int child_pid;
	pthread_t monitor_thread;
	pthread_t writer_thread;
	lst = lst_new();
	writing_queue = new_queue();

	/* Initialize synchronization objects */
	pthread_mutex_init_(&mutex, NULL);
	pthread_cond_init_(&write_cond, 0);
	pthread_cond_init_(&max_par, NULL);
	pthread_cond_init_(&new_child, NULL);

	if ((log_fd = fopen("./log.txt", "a+")) == NULL){
		perror("[ERROR] opening log file");
		exit(EXIT_FAILURE);
	}
	read_log(); /* assign total time and iteration values for this execution */
	pthread_create_(&monitor_thread, NULL, (void *)&monitor, NULL); /* Create Monitor Thread */  
	pthread_create_(&writer_thread, NULL, (void *)&writer, NULL); /* Create Writer Thread */
 
	while (1) {
		numArgs = readLineArguments(arg_vector, VECTOR_SIZE, buffer, BUFFER_SIZE);
		if (numArgs <= 0)continue;

		if (strcmp(arg_vector[0], EXIT_COMMAND) == 0 ) {

			/* signal exit command */
			exit_command = 1;

			/* wait for monitor thread to end */
			pthread_cond_signal_(&new_child); /* must signal to catch exit flag */
			pthread_join_(monitor_thread, NULL);
			pthread_join_(writer_thread, NULL);

			/* print all the elements in the list */
			lst_print(lst);
			
			/* terminate sync objects */
			pthread_mutex_destroy_(&mutex);
			pthread_cond_destroy_(&write_cond);
			pthread_cond_destroy_(&max_par);
			pthread_cond_destroy_(&new_child);
			fclose(log_fd);
			lst_destroy(lst);
			exit(EXIT_SUCCESS);
		}

		/* while there are child process slots available launch new child process,
		* else wait here */
		pthread_mutex_lock_(&mutex);
		while (child_count >= MAXPAR) pthread_cond_wait_(&max_par, &mutex);
		pthread_mutex_unlock_(&mutex);

		child_pid = fork();
		if (child_pid < 0){ /* test for error in fork */
			perror("[ERROR] forking process");
			continue;
		}
		if (child_pid == 0){ /* execute on child */
			if (execv(arg_vector[0], arg_vector) == -1) {
			perror("[ERROR] executing program.");
			exit(EXIT_FAILURE);
			}
		}
		else { /* execute on parent */
			/* Main thread
			 *
			 * Child processes are inserted into the process list saving their pid
			 * and their start time.
			 * Child counter is incremented.
			 * The condition variable waiting for a new child process is signaled.
 			 */
			time(&starttime); /* get start time of child process */
			pthread_mutex_lock_(&mutex);
			insert_new_process(lst, child_pid, starttime);
			child_count++;
			pthread_cond_signal_(&new_child);
			pthread_mutex_unlock_(&mutex);
		}
	}
}
Exemple #7
0
int
dspio_readHB_mat_double( const char* filename,
                         int row_i, int row_f,
                         int** p_rowptr,
                         int* p_nnz,
                         int** p_colind,
                         double** p_val )
{
/****************************************************************************/
/*  This function opens and reads the specified file, interpreting its      */
/*  contents as a sparse matrix stored in the Harwell/Boeing standard       */
/*  format and creating compressed column storage scheme vectors to hold    */
/*  the index and nonzero value information.                                */
/*                                                                          */
/*    ----------                                                            */
/*    **CAVEAT**                                                            */
/*    ----------                                                            */
/*  Parsing real formats from Fortran is tricky, and this file reader       */
/*  does not claim to be foolproof.   It has been tested for cases when     */
/*  the real values are printed consistently and evenly spaced on each      */
/*  line, with Fixed (F), and Exponential (E or D) formats.                 */
/*                                                                          */
/*  **  If the input file does not adhere to the H/B format, the  **        */
/*  **             results will be unpredictable.                 **        */
/*                                                                          */
/****************************************************************************/
  FILE *in_file;
  int i,j,ind,col,offset,count,last,Nrhs;
  int Ptrcrd, Indcrd, Valcrd, Rhscrd;
  int Nrow, Ncol, Nnzero;
  int Ptrperline, Ptrwidth, Indperline, Indwidth;
  int Valperline, Valwidth, Valprec;
  int Valflag;           /* Indicates 'E','D', or 'F' float format */
  char* ThisElement;
  char Title[73], Key[9], Type[4], Rhstype[4];
  char Ptrfmt[17], Indfmt[17], Valfmt[21], Rhsfmt[21];
  char line[BUFSIZ];

  int* rowptr;
  int* colind;
  int  len_colind;
  double* val;
  int  nr = row_f - row_i + 1;
  int  temp_elem;
  int  rownum;
  int  running_offset;
  int  new_insert_pos;

  list_t* symm_entries;    /* store list of symmetric entries to add */
  int* all_rowptr;
  int len_extra_symm;   /* # of extra entries due to symmetry */
  fpos_t save_pos;

  dlist_t* symm_vals;
  fpos_t val_save_pos;
  FILE*  val_in_file;
  char val_line[BUFSIZ];
  int val_col;
  int val_ind;
  int val_i;
  int val_skip_lines;
  char* val_ThisElement;
  double val_temp_elem;

  in_file = fopen( filename, "r");
  assert( in_file != NULL );

  readHB_header(in_file, Title, Key, Type, &Nrow, &Ncol, &Nnzero, &Nrhs,
                Ptrfmt, Indfmt, Valfmt, Rhsfmt,
                &Ptrcrd, &Indcrd, &Valcrd, &Rhscrd, Rhstype);

  assert( Nrow == Ncol );
  assert( Type[0] == 'R' || Type[0] == 'r' );
  assert( Type[1] == 'S' || Type[1] == 's' );
  assert( Type[2] == 'A' || Type[2] == 'a' );

  /*  Parse the array input formats from Line 3 of HB file  */
  ParseIfmt(Ptrfmt,&Ptrperline,&Ptrwidth);
  ParseIfmt(Indfmt,&Indperline,&Indwidth);
  ParseRfmt(Valfmt,&Valperline,&Valwidth,&Valprec,&Valflag);

  /*  Read row pointer array:   */
  offset = 1;

  rowptr = (int *)malloc( sizeof(int)*(nr + 1) );
  *p_rowptr = rowptr;
  if( rowptr == NULL )
    IOHBTerminate( "Out of memory allocating row pointer" );

  all_rowptr = (int *)malloc( sizeof(int)*(row_f+2) );
  if( all_rowptr == NULL )
    IOHBTerminate( "Out of memory allocating all row pointer" );

  symm_entries = (list_t *)malloc( sizeof(list_t)*(row_f+1) );
  symm_vals = (dlist_t *)malloc( sizeof(dlist_t)*(row_f+1) );
  if( symm_entries == NULL || symm_vals == NULL )
    IOHBTerminate( "Out of memory allocating symmetric entries" );
  for( i = 0; i < (row_f+1); i++ ) {
    lst_init( &(symm_entries[i]) );
    dlst_init( &(symm_vals[i]) );
  }

  ThisElement = (char *) malloc(Ptrwidth+1);
  if ( ThisElement == NULL )
    IOHBTerminate("Insufficient memory for ThisElement (1).");
  *(ThisElement+Ptrwidth) = (char) NULL;
  count = 0;
  for( i = 0; i < Ptrcrd; i++ ) {
    fgets( line, BUFSIZ, in_file );
    if ( sscanf(line, "%*s") < 0 ) 
      IOHBTerminate("--- Null (or blank) line in ptr data region ---\n");
    col = 0;
    for( ind = 0; ind < Ptrperline; ind++ ) {

      if( count > Ncol || count > row_f+1 )
        break;

      /* copy and convert index */
      strncpy( ThisElement, line+col, Ptrwidth );
      temp_elem = atoi(ThisElement) - offset;

      if( count >= row_i ) {
        /* only save elements in the proper range for this processor */
        rowptr[ count - row_i ] = temp_elem;
      }

      all_rowptr[ count ] = temp_elem;

      count++;
      col += Ptrwidth;
    }
  }
  free(ThisElement);

#ifndef NDEBUG_IO
fprintf( stderr, "printing rowptr...\n" );
for( i = 0; i <= nr; i++ )
  fprintf( stderr, "rowptr[%d]==%d\n", i, rowptr[i] );
fprintf( stderr, "printing all_rowptr...\n" );
for( i = 0; i <= row_f+1; i++ )
  fprintf( stderr, "all_rowptr[%d]==%d\n", i, all_rowptr[i] );
#endif


  /* alloc space for column indices and values */

  ThisElement = (char *) malloc(Indwidth+1);
  if ( ThisElement == NULL )
    IOHBTerminate("Insufficient memory for ThisElement (2).");
  *(ThisElement+Indwidth) = (char) NULL;
  val_ThisElement = (char *) malloc(Valwidth+2);
  if ( val_ThisElement == NULL )
    IOHBTerminate("Insufficient memory for val_ThisElement (2).");
  *(val_ThisElement+Valwidth) = (char) NULL;
  *(val_ThisElement+Valwidth+1) = (char) NULL;

  len_extra_symm = 0;
  fgetpos( in_file, &save_pos );
  rownum = 0;

  /* position at analogous place in file for values */
  val_in_file = fopen( filename, "r" );
  assert( val_in_file != NULL );
  val_skip_lines = 4 + (Rhscrd > 0) + Ptrcrd + Indcrd;

#ifndef NDEBUG_IO
fprintf( stderr, "header lines: %d (%d), ptr lines: %d, ind lines: %d\n",
         4 + (Rhscrd>0), Rhscrd, Ptrcrd, Indcrd );
fprintf( stderr, "skipping %d lines to get to vals...\n", val_skip_lines );
#endif

  for( i = 0; i < val_skip_lines; i++ ) {
    fgets( line, BUFSIZ, val_in_file );
  }
  fgetpos( val_in_file, &val_save_pos );

  count = 0;
  /*  for( i = 0; i < Indcrd; i++ ) {*/
  i = 0;       /* line number */
  col = 0;     /* column number on a given line */
  ind = 0;     /* item number on a given line */
  val_col = 0; /* analogous */
  val_ind = 0;
  val_i = 0;
  while( i <= Indcrd ) {

    /* read new lines, if necessary */
    if( (ind % Indperline) == 0 ) {
      fgets( line, BUFSIZ, in_file );
      if ( sscanf(line,"%*s") < 0 )
        IOHBTerminate("--- Null (or blank) line in index data region ---\n");
      i++;

      col = 0;
    }

    if( (val_ind % Valperline) == 0 ) {
      fgets( val_line, BUFSIZ, val_in_file );
      if( sscanf(val_line, "%*s") < 0 )
        IOHBTerminate("--- Null (or blank) line in value region ---\n");
      val_i++;

      val_col = 0;

      if( Valflag == 'D' ) {
        while( strchr(val_line, 'D') ) *strchr(val_line,'D') = 'E';
      }
    }

    if (count == Nnzero) break;

    /* read an entry from this line */
    strncpy( ThisElement, line+col, Indwidth );
    col += Indwidth;
    ind++;

    strncpy( val_ThisElement, val_line + val_col, Valwidth );
    *(val_ThisElement+Valwidth) = (char) NULL;
    val_col += Valwidth;
    val_ind++;
    if ( Valflag != 'F' && strchr(val_ThisElement,'E') == NULL ) {
      /* insert a char prefix for exp */
      last = strlen(val_ThisElement);
      for (j=last+1;j>=0;j--) {
        val_ThisElement[j] = val_ThisElement[j-1];
        if ( val_ThisElement[j] == '+' || val_ThisElement[j] == '-' ) {
          val_ThisElement[j-1] = Valflag;
          break;
        }
      }
    }

    /* done */
    if( count >= rowptr[nr] )
      break;

    temp_elem = atoi( ThisElement ) - offset;
    val_temp_elem = atof( val_ThisElement );

#ifndef NDEBUG_IO
    fprintf( stderr, "found: %d (%f)\n", temp_elem, val_temp_elem );
#endif

    if( temp_elem >= row_i && temp_elem <= row_f ) {
      if( temp_elem != rownum ) { /* ignore diagonal entry */

#ifndef NDEBUG_IO
        fprintf( stderr, "new entry: (%d, %d) == %f\n",
                 temp_elem, rownum, val_temp_elem );
#endif

        len_extra_symm++;
        lst_insert( &(symm_entries[temp_elem]), rownum );
        dlst_insert( &(symm_vals[temp_elem]), val_temp_elem );
      }
    }

    count++;
    if( count >= all_rowptr[rownum+1] )
      rownum++;
  }


#ifndef NDEBUG_IO
fprintf( stderr, "extra entries due to symmetry: %d\n", len_extra_symm );
#endif

  len_colind = rowptr[nr] - rowptr[0] + len_extra_symm;
  *p_nnz = len_colind;
  colind = (int *)malloc( sizeof(int)*len_colind );
  *p_colind = colind;

#ifndef NDEBUG_IO
fprintf( stderr, "nnz == %d\n", len_colind );
#endif

  val = (double *)malloc( sizeof(double)*len_colind );
  *p_val = val;

  assert( colind != NULL && val != NULL );

  /*  Read column index array:  */
  fsetpos( in_file, &save_pos );
  i = 0;
  col = 0;
  ind = 0;

  fsetpos( val_in_file, &val_save_pos );
  val_i = 0;
  val_col = 0;
  val_ind = 0;

  count = 0;
  rownum = 0;
  running_offset = 0;

  while( i <= Indcrd ) {

    /* read new lines, if necessary */
    if( (ind % Indperline) == 0 ) {
      fgets( line, BUFSIZ, in_file );
      if ( sscanf(line,"%*s") < 0 )
        IOHBTerminate("--- Null (or blank) line in index data region ---\n");
      i++;

      col = 0;
    }

    if( (val_ind % Valperline) == 0 ) {
      fgets( val_line, BUFSIZ, val_in_file );
      if( sscanf(val_line, "%*s") < 0 )
        IOHBTerminate("--- Null (or blank) line in value region ---\n");
      val_i++;

      val_col = 0;

      if( Valflag == 'D' ) {
        while( strchr(val_line, 'D') ) *strchr(val_line,'D') = 'E';
      }
    }


    if (count == Nnzero) break;


    /* read an entry from this line */
    strncpy( ThisElement, line+col, Indwidth );
    col += Indwidth;
    ind++;

    strncpy( val_ThisElement, val_line + val_col, Valwidth );
    *(val_ThisElement+Valwidth) = (char) NULL;
    val_col += Valwidth;
    val_ind++;
    if ( Valflag != 'F' && strchr(val_ThisElement,'E') == NULL ) {
      /* insert a char prefix for exp */
      last = strlen(val_ThisElement);
      for (j=last+1;j>=0;j--) {
        val_ThisElement[j] = val_ThisElement[j-1];
        if ( val_ThisElement[j] == '+' || val_ThisElement[j] == '-' ) {
          val_ThisElement[j-1] = Valflag;
          break;
        }
      }
    }

    /* done */
    if( count >= all_rowptr[nr + row_i] )
      break;

    temp_elem = atoi( ThisElement ) - offset;
    val_temp_elem = atof( val_ThisElement );

#ifndef NDEBUG_IO
    fprintf( stderr, "entry: (%d, %d) == %f\n", rownum, temp_elem, val_temp_elem );
#endif

    if( count >= all_rowptr[ row_i ] ) {
      new_insert_pos = count - all_rowptr[row_i] + running_offset;

#ifndef NDEBUG_IO
      fprintf( stderr, "inserting into colind[%d]: %d\n",
               new_insert_pos, temp_elem );
#endif
      colind[ new_insert_pos ] = temp_elem;
      val[ new_insert_pos ] = val_temp_elem;
    }

    count++;
    if( count >= all_rowptr[rownum+1] ) {
      rownum++;

      if( rownum >= row_i && rownum <= row_f+1 ) {
#ifndef NDEBUG_IO
        fprintf( stderr, "rowptr[%d] (== %d) += %d\n", rownum - row_i, rowptr[ rownum - row_i ], running_offset );
#endif
        rowptr[ rownum - row_i ] += running_offset;
      }

      if( rownum >= row_i && rownum <= row_f ) {
        /* insert symmetric entries, if any */
        int new_additions = 0;
        list_node_t* trace = symm_entries[rownum].head;
        dlist_node_t* dtrace = symm_vals[rownum].head;

#ifndef NDEBUG_IO
        fprintf( stderr, "symm_entry[%d].length == %d\n", rownum, symm_entries[rownum].length );
#endif

        new_insert_pos = count - all_rowptr[row_i] + running_offset;
        while( trace != NULL ) {
          assert( dtrace != NULL );

#ifndef NDEBUG_IO
          fprintf( stderr, "inserting symmetric entry: colind[%d] = %d\n",
                   new_insert_pos + new_additions, trace->value );
          fprintf( stderr, "inserting symmetric value: val[%d] = %f\n",
                   new_insert_pos + new_additions, dtrace->value );
#endif
          colind[ new_insert_pos + new_additions ] = trace->value;
          val[ new_insert_pos + new_additions ] = dtrace->value;
          trace = trace->next;
          dtrace = dtrace->next;
          new_additions++;
        } /* while */
        assert( new_additions == symm_entries[rownum].length );
        assert( new_additions == symm_vals[rownum].length );
        running_offset += new_additions;
      } /* rownum >= row_i ... */
    } /* count >= ... */
  }

  free(ThisElement);
  free(val_ThisElement);


  for( i = 0; i < row_f+1; i++ ) {
    lst_destroy( &(symm_entries[i]) );
  }
  for( i = 0; i < row_f+1; i++ ) {
    dlst_destroy( &(symm_vals[i]) );
  }
  free( symm_entries );
  free( symm_vals );
  free( all_rowptr );

  fclose( in_file );
  fclose( val_in_file );
  return 1;
}
/*////////////////////////////////////////////
/////////////// MAIN FUNCTION ////////////////
////////////////////////////////////////////*/
int main() {
	char* arg[7];
	char buffer[100], filename[100], fnamePipeStats[100];
	int vectorSize = 7, pid, numargs, fd, fDescPIPE, fDescPIPE_S;
	pthread_t waitChild;
	pid_t pidChild;
	terminalLst* terminals = new_terminal_lst();
	l = lst_new();
	if (pthread_mutex_lock(&mutex) != 0) {
		perror(error_mutex_lock);
	}
	if (pthread_mutex_unlock(&mutex) != 0) {
		perror(error_mutex_unlock);
	}
    
	if (pthread_mutex_init(&mutex, NULL) != 0){
		perror(error_mutex);
	}
	if (pthread_cond_init(&can_wait, NULL) != 0) {
		perror(error_cond_init_wait);
	}
	if (pthread_cond_init(&can_execute, NULL) != 0) {
		perror(error_cond_init_execute);
	}
	if (pthread_create(&waitChild, NULL, waitThread, NULL) != 0) {
		perror(error_thread_create);
		exit(EXIT_FAILURE);
	}
    if (signal(SIGINT, CTRLC) == SIG_ERR) {
        perror(error_signal);
    }
	unlink(PIPE); /*-------------------------------------------------*/

	if (mkfifo(PIPE, 0777) != 0) {
		perror(error_mkfifo);
		exit(EXIT_FAILURE);
	}
	if ((fDescPIPE = open(PIPE, O_RDONLY)) == -1) {
		perror(error_pipe_open);
		exit(EXIT_FAILURE);
	}

	close(0);
	dup2(fDescPIPE, 0);

	while (1) {

		numargs = readLineArguments(arg, vectorSize, buffer, 100);

		if(flag_signal)
			break;

		if (numargs <= 1) {
			continue;
		}
		
		if (pthread_mutex_lock(&mutex) != 0) {
			perror(error_mutex_lock);
		}
		while (numChildren == MAXPAR) {
            if (pthread_cond_wait(&can_execute, &mutex) != 0) {
                perror(error_cond_wait);
            }
		}
		if (pthread_mutex_unlock(&mutex) != 0) {
			perror(error_mutex_unlock);
		}
		else if (strcmp(arg[0], EXIT) != 0) {
			if (strcmp(arg[0], starter) == 0) {
				int pid_terminal = atoi(arg[1]);
				insert_terminal(terminals, pid_terminal);
				continue;
			}
			if (strcmp(arg[0], stats) == 0) { /*tratar o PID e meter na lista*/
				sprintf(fnamePipeStats, "%s-%s", PIPE_S, arg[1]);
                
                while((fDescPIPE_S = open(fnamePipeStats, O_WRONLY)) < 0);
                if(fDescPIPE < 0) {
					perror(error_pipe_open);
					exit(EXIT_FAILURE);
				}
				if (pthread_mutex_lock(&mutex) != 0) {
                    perror(error_mutex_lock);
                }

				sprintf (buffer, "Number of active children: %d\nTotal execution time to the moment: %d", numChildren, timeTotal);
				write(fDescPIPE_S, buffer, strlen(buffer));
                if (pthread_mutex_unlock(&mutex) != 0) {
                    perror(error_mutex_unlock);
                }

				close(fDescPIPE_S);
				continue;
			}

            if (strcmp(arg[0], EXITGLOBAL) == 0) { /* SONFOILULDNILDEFNC*/
                printf("1\n");
                CTRLC(SIGINT);
            }
			else {
				pid = fork();
				if (pid < 0) {
					perror(error_fork);
				}
				if (pthread_mutex_lock(&mutex) != 0) {
					perror(error_mutex_lock);
				}
				insert_new_process(l, pid, time(NULL));
				numChildren++;
				if (pthread_cond_signal(&can_wait) != 0) {
					perror(error_cond_wait);
				}
				if (pthread_mutex_unlock(&mutex) != 0) {
					perror(error_mutex_unlock);
				}
				if (pid == 0) {
					pidChild = getpid();
					sprintf(filename, "par-shell-%d.txt", pidChild);
					fd = open(filename,  O_CREAT | O_WRONLY, S_IRUSR | S_IWUSR);
					close(1);
					dup(fd);
					close(fd);
					if (execv(arg[0], arg) < 0) {
						perror(error_execv);
						exit(EXIT_FAILURE);
					}
				}
				else {
					sprintf(filename, "par-shell-%d.txt", pid);
				}
			}
        }
        else {
            break;
        }
	}
	isExit = true;
    if (pthread_cond_signal(&can_wait) != 0) {
        perror(error_cond_wait);
    }
    if (pthread_mutex_unlock(&mutex) != 0) {
        perror(error_mutex_unlock);
    }
    if (pthread_join(waitChild, NULL) != 0) {
        perror(error_thread_join);
    }
    lst_print(l);
    lst_destroy(l);
    while(remove_terminal(terminals)!= -1){

    }
    if (pthread_cond_destroy(&can_wait) != 0) {
        perror(error_cond_destroy_wait);
    }
    if (pthread_cond_destroy(&can_execute) != 0) {
        perror(error_cond_destroy_execute);
    }
    exit(EXIT_SUCCESS);
	return 0;
}
static void		delete_polygons(void *polygon_ptr)
{
	t_polygon	*polygon = (t_polygon *)polygon_ptr;

	lst_destroy(&polygon->vertices, free);
}
Exemple #10
0
int main() {
  int inputPipe;
  char buffer[BUFFER_LEN];
  char mktemp_filename[PATH_MAX];
  char mktemp_dir[PATH_MAX];
  int ret;
  int terminalPid;
  TerminalList * termlist = lst_new();
  pthread_t threadMonitor;
  char *args[N_ARGS];
  if (signal(SIGINT, handleSIGINT)) {
    fprintf(stderr, "Could not set sigint handler!\n");
    exit(EXIT_FAILURE);
  }
  if (pthread_mutex_init(&mutexRunningProcesses, NULL)) {
    fprintf(stderr, "Could not create runningProcesses mutex\n");
    exit(EXIT_FAILURE);
  }
  if (pthread_cond_init(&condRunningProcesses, NULL)) {
    fprintf(stderr, "Could not create runningProcesses cond\n");
    exit(EXIT_FAILURE);
  }
  if (pthread_cond_init(&condFreeSlots, NULL)) {
    fprintf(stderr, "Could not create FreeSlots cond\n");
    exit(EXIT_FAILURE);
  }

  strcpy(mktemp_dir, MKTEMP_TEMPLATE);
  TESTTRUE(mkdtemp(mktemp_dir)!=NULL, "Erro na criação do diretorio temporário (" _AT_ ")\n");
  strncpy(mktemp_filename, mktemp_dir, PATH_MAX);
  strncpy(mktemp_filename+strlen(mktemp_filename), "/" INPUT_FILE, PATH_MAX-strlen(mktemp_filename));
  fprintf(stdin, "Ficheiro de input: '%s'\n", mktemp_filename);
  if (mkfifo(mktemp_filename, 0660) <0) {
    fprintf(stderr, "Could not create fifo %s\n", mktemp_filename);
    exit(EXIT_FAILURE);
  }
  printf("A abrir o pipe %s para leitura...\n", mktemp_filename);
  if ((inputPipe = open(mktemp_filename, O_RDONLY)) < 0) {
    fprintf(stderr, "Could not create fifo " INPUT_FILE "\n");
    exit(EXIT_FAILURE);
  }
  printf("A abrir o pipe %s para escrita...\n", mktemp_filename);
  if ((outPipe = open(mktemp_filename, O_WRONLY|O_NONBLOCK)) < 0) {
    fprintf(stderr, "Erro ao abrir o ficheiro de output" INPUT_FILE "\n");
    exit(EXIT_FAILURE);
  }
  initProcessList();
  if(pthread_create(&threadMonitor, 0,processMonitor, NULL)!= 0) {
    printf("Erro na criação da tarefa\n");
    exit(EXIT_FAILURE);
  }

  while(1) {
    if (exitCalled) break;
    if (readFromPipe(inputPipe, buffer, &terminalPid, termlist)!=0) continue;
    printf("Comando: %s\n", buffer);
    ret = readLineArguments(args, N_ARGS, buffer, BUFFER_LEN);
    if (!ret) continue;
    processesWaitingToRun++;
    newProcess(args, terminalPid);
  }

  //Mata todos os processos de terminal
  lst_destroy(termlist);

  C_SIGNAL(&condRunningProcesses);

  pthread_join(threadMonitor, NULL);



  //The following function is called after all threads have joined, therefore there aren't used any mutexes
  exitParShell();
  endProcessList();

  pthread_mutex_destroy(&mutexRunningProcesses);
  pthread_cond_destroy(&condRunningProcesses);
  pthread_cond_destroy(&condFreeSlots);
  close(inputPipe); //aqui nao faz sentido testar o return destas funcoes
  close(outPipe); //aqui nao faz sentido testar o return destas funcoes
  unlink(INPUT_FILE); //aqui nao faz sentido testar o return destas funcoes

  return EXIT_SUCCESS;
}