Line data Source code
1 : #include "background_manager.h" 2 : 3 : static BackgroundProcess background_processes[MAX_BACKGROUND_PROCESSES]; 4 : static size_t num_background_processes = 0; 5 : 6 18 : void check_completed_background_processes() 7 : { 8 18 : size_t i = 0; 9 20 : while (i < num_background_processes) 10 : { 11 2 : pid_t pid = background_processes[i].pid; 12 : int status; 13 2 : int result = waitpid(pid, &status, WNOHANG); 14 2 : if (result == -1) 15 : { 16 0 : perror("waitpid"); 17 : } 18 2 : else if (result > 0) 19 : { // The process with PID 'pid' has completed 20 : // Display the correct symbol based on the exit status 21 1 : char symbol = i == num_background_processes - 1 ? '+' : i == num_background_processes - 2 ? '-' 22 : : ' '; 23 1 : printf("[%d]%c Done %s\n", background_processes[i].job_number, symbol, background_processes[i].command); 24 : 25 : // Free the memory for the completed process command 26 1 : free(background_processes[i].command); 27 : 28 : // Remove the completed process from the list 29 1 : for (size_t j = i; j < num_background_processes - 1; ++j) 30 : { 31 0 : background_processes[j] = background_processes[j + 1]; 32 : } 33 1 : num_background_processes--; 34 : } 35 : else 36 : { 37 : // Move to the next background process if the current one hasn't completed 38 1 : i++; 39 : } 40 : } 41 18 : } 42 : 43 1 : void add_background_process(pid_t pid, const Command *command) 44 : { 45 1 : background_processes[num_background_processes].pid = pid; 46 1 : background_processes[num_background_processes].job_number = num_background_processes + 1; 47 1 : background_processes[num_background_processes].command = strdup(command->input_string); 48 : 49 1 : if (background_processes[num_background_processes].command == NULL) { 50 0 : perror("strdup"); 51 0 : exit(EXIT_FAILURE); 52 : } 53 : 54 1 : printf("[%d] %d %s\n", background_processes[num_background_processes].job_number, pid, background_processes[num_background_processes].command); 55 1 : num_background_processes++; 56 1 : }