Foocli
Foocli

Reputation: 167

why my handler does not give me the exit status in C?

currently I have the code like that:

void handler(int sig) {
  int stat;
  wait(&stat);
  if (WIFEXITED(stat))
    printf("%d", WEXITSTATUS(stat));
}
int main() {
  int i;
  pid_t pids[5];
  signal(SIGCHLD, handler);
  for (i=0; i<5; i++)
    if ((pids[i] = fork()) == 0) {
      printf("1");
      while (1) ; /* inf loop */
    }
  for (i=0; i<5; i++)
    kill(pids[i], SIGKILL);
  sleep(1);
  return 2;
}

All necessary head files were included such as <signal.h> and <stdlib.h>

I assume that I would at least get the exit status when running, but there is no output. Why is that?

Upvotes: 0

Views: 258

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409196

But the child processes don't exit, they are killed. They are terminated by a signal. Use WIFSIGNALED to check if the process was killed by a signal, and WTERMSIG to get the signal number.

For a process to "exit" it has to either return from the main function, or call exit.

Upvotes: 1

Related Questions