Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to determine program crash

Tags:

c

linux

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.

like image 434
NewMrd Avatar asked May 31 '26 17:05

NewMrd


1 Answers

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:

  • man 3 exec
  • man 3 wait
  • http://www.yolinux.com/TUTORIALS/ForkExecProcesses.html
like image 177
phoxis Avatar answered Jun 04 '26 02:06

phoxis



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!