NewMrd
NewMrd

Reputation: 431

How to determine program crash

How i can determine the running program is crashed or terminated successfully?

I run the program with system('exe'), and i have the source code of 'exe' in C?

I prefer a solution like adding some code to 'exe's code. like atexit(someFunction) - but atexit is not working on exceptions-.

I'm using Linux.

Upvotes: 3

Views: 2584

Answers (1)

phoxis
phoxis

Reputation: 61910

system returns:

The value returned is -1 on error (e.g., fork(2) failed), and the return status of the command otherwise. This latter return status is in the format specified in wait(2). Thus, the exit code of the command will be WEXITSTATUS(status). In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127).

Therefor store the return value of the system call and then check the return value. If your "exe" returns a success code you will know it has terminated successfully, or else if specific error code is returned by your code then you will know what error was that, else you can assume the code crashed.

As Ingo Leonhardt told in the comment, you can check for signals using the WTERMSIG() and WIFSIGNALED() macros to test the returned value by system function call to check if a signal occurred and if yes then which one.

Here is a quick example:

bad.c Will segfault.

#include <stdio.h>

int main (void)
{
  char *p = "Hello";

  p[1] = 'X';

  return 1;
}

system.c executes bad.

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>

int main (void)
{
  int retval;

  retval = system ("./bad");
  if (!WIFSIGNALED(retval))
  {
    printf ("Process completed successfully\n");
  }
  else
  {
    switch (WTERMSIG(retval))
    {
      case SIGINT: printf ("SIGINT\n");
                 break;
      case SIGSEGV: printf ("SIGSEGV\n");
                  break;

      case SIGQUIT: printf ("SIGQUIT\n");
                  break;
    }
  }
  printf ("EXIT STATUS: %d\n", WEXITSTATUS(retval));
  return 0;
}  

But the recommended process is to use exec family and wait family in these cases. These will give you much better control on the executing of the process.

See:

Upvotes: 5

Related Questions