简体   繁体   English

如何确定程序崩溃

[英]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 ? 我用system('exe')运行程序,我在C'exe'的源代码?

I prefer a solution like adding some code to 'exe's code. 我更喜欢像'exe's代码一样添加一些代码的解决方案。 like atexit(someFunction) - but atexit is not working on exceptions -. atexit(someFunction) - 但是atexit没有处理exceptions - 。

I'm using Linux. 我正在使用Linux。

system returns: system返回:

The value returned is -1 on error (eg, fork(2) failed), and the return status of the command otherwise. 返回的值在出错时为-1(例如,fork(2)失败),否则返回命令的返回状态。 This latter return status is in the format specified in wait(2). 后一种返回状态采用wait(2)中指定的格式。 Thus, the exit code of the command will be WEXITSTATUS(status). 因此,命令的退出代码将是WEXITSTATUS(状态)。 In case /bin/sh could not be executed, the exit status will be that of a command that does exit(127). 如果无法执行/ bin / sh,则退出状态将是退出(127)的命令的退出状态。

Therefor store the return value of the system call and then check the return value. 因此存储system调用的返回值,然后检查返回值。 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. 如果您的“exe”返回成功代码,您将知道它已成功终止,否则如果您的代码返回了特定的错误代码,那么您将知道该错误是什么,否则您可以假设代码崩溃。

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. 正如Ingo Leonhardt在评论中所说,您可以使用WTERMSIG()WIFSIGNALED()宏来检查信号,以通过system函数调用来检查返回的值,以检查是否发生了信号,如果是,则检查是哪一个。

Here is a quick example: 这是一个简单的例子:

bad.c Will segfault. bad.c将是段错误。

#include <stdio.h>

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

  p[1] = 'X';

  return 1;
}

system.c executes bad. system.c执行错误。

#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. 但推荐的过程是在这些情况下使用exec系列并wait系列。 These will give you much better control on the executing of the process. 这些将使您更好地控制流程的执行。

See: 看到:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM