Skip to content

Commit

Permalink
removed global error code, and returned the leftmost error code from …
Browse files Browse the repository at this point in the history
…the command list
  • Loading branch information
DylanSale committed Oct 7, 2015
1 parent 08fc237 commit e3868df
Showing 1 changed file with 23 additions and 15 deletions.
38 changes: 23 additions & 15 deletions main.c
Original file line number Diff line number Diff line change
Expand Up @@ -7,24 +7,27 @@
#include <stdio.h>
#include <string.h>
#include <signal.h>
#include <limits.h>

#define WAIT_FOR_PROC_DEATH_TIMEOUT 10
#define MAX_CMDS 16
#define SEP "---"

#undef NDEBUG

// TODO: sig_atomic_t (although it is typedefd to int :P)
// used as boolean by signal handlers to tell process it should exit
static volatile int running = 1;

static int error_code = 0;

static void wait_for_requested_commands_to_exit(int n_cmds, pid_t *pids) {
static int wait_for_requested_commands_to_exit(int n_cmds, pid_t *pids) {
int cmds_left = n_cmds;
int error_code = 0;
int error_code_idx = INT_MAX;

for (;;) {
int status;

if (! running) return;
if (! running) return error_code;
pid_t waited_pid = waitpid(-1, &status, 0);
if (waited_pid == -1) {
if (errno == EINTR) {
Expand All @@ -38,20 +41,23 @@ static void wait_for_requested_commands_to_exit(int n_cmds, pid_t *pids) {
# endif
}
}
if (! running) return;
if (! running) return error_code;

// check for pid in list of child pids
for (int i = 0; i < n_cmds; ++i) {
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
# ifndef NDEBUG
fprintf(stderr, "process exit with status: %d \n", exit_status);
# endif
error_code = exit_status;
}


if (pids[i] == waited_pid) {
if (WIFEXITED(status)) {
int exit_status = WEXITSTATUS(status);
# ifndef NDEBUG
fprintf(stderr, "process exit with status: %d \n", exit_status);
# endif
if (exit_status != 0 && i < error_code_idx) {
error_code = exit_status;
error_code_idx = i;
}
}

# ifndef NDEBUG
fprintf(stderr, "process exit: %d in command list, %d left\n", waited_pid, cmds_left - 1);
# endif
Expand All @@ -60,7 +66,7 @@ static void wait_for_requested_commands_to_exit(int n_cmds, pid_t *pids) {
# ifndef NDEBUG
fprintf(stderr, "all processes exited\n");
# endif
return;
return error_code;
}
break;
}
Expand All @@ -71,6 +77,8 @@ static void wait_for_requested_commands_to_exit(int n_cmds, pid_t *pids) {
# endif
}
}

return error_code;
}

static void wait_for_all_processes_to_exit() {
Expand Down Expand Up @@ -167,7 +175,7 @@ int main(int argc, char *argv[]) {
cmds[n_cmds++] = run_proc(cmd_begin);
}

wait_for_requested_commands_to_exit(n_cmds, cmds);
int error_code = wait_for_requested_commands_to_exit(n_cmds, cmds);
remove_term_and_int_handlers();
alarm(WAIT_FOR_PROC_DEATH_TIMEOUT);
kill(0, SIGTERM);
Expand Down

0 comments on commit e3868df

Please sign in to comment.