void ft_free_map(t_map map) { map.room = free_room(map.room); map.pipes = free_pipes(map.pipes); free(map.room); free(map.pipes); }
t_pipes *free_pipes(t_pipes *pipes) { t_pipes *tmp; if (pipes == NULL) return (NULL); else { tmp = pipes->next; free(pipes); return (free_pipes(tmp)); } }
int execute( const List_t* list) { Node_t* curr = list->head->next; int files = -1; int** pipes = make_pipes( list->count - 1); if( !pipes) return 0; int outPipe[2] = {}; pipe( outPipe); if( outPipe[0] < 0 || outPipe[1] < 0) { warn( "Error while creating outPipe"); return 0; } char* argv[ARGUMENTS_NUMBER] = {}; int i = 0; pid_t pid = 0; int status = -1; while( curr) { make_argv( curr->program, argv); files = open_files( curr->program); if( (pid = fork()) == 0) { if( curr->program->input >= 0) { if( dup2( curr->program->input, 0) < 0) warn( "Error while getting input from file %s", curr->program->input_name); } else if( i > 0) { if( dup2( pipes[i - 1][0], 0) < 0) warn( "Error while piping input for program %d", i); } if( curr->program->output >= 0) if( dup2( curr->program->output, 1) < 0) warn( "Error while sending output to file %s", curr->program->output_name); if( curr->type == last && curr->program->output < 0) if( dup2( outPipe[1], 1) < 0) warn( "Error while sending output to final pipe"); if( curr->type != last && curr->program->output < 0) if( dup2( pipes[i][1], 1) < 0) warn( "Error while piping output for program %d", i); close_pipes( pipes, list->count - 1); if( outPipe[0] > 0) close( outPipe[0]); if( outPipe[1] > 0) close( outPipe[1]); free_pipes( pipes, list->count - 1); if( files != close_files( curr->program)) warn( "Error while closing files in child"); if( execvp( curr->program->name, argv) < 0) { warn( "Error while executing %s", curr->program->name); exit( -1); } } if( curr->type == last) { close_pipes( pipes, list->count - 1); if( outPipe[1] > 0) close( outPipe[1]); print_output( outPipe[0]); if( outPipe[0] > 0) close( outPipe[0]); waitpid( pid, &status, 0); printf("Process exited with status %d\n", status); } if( files != close_files( curr->program)) warn( "Error while closing files in parrent"); curr = curr->next; ++i; } free_pipes( pipes, list->count - 1); return 1; }