Strange behavior of C abort function on mingw-w64

只谈情不闲聊 提交于 2021-01-29 03:59:59

问题


I'm new to mingw-w64 and I'm running into the following problem:

I recently installed MSYS on my Windows 10 computer according to the instructions provided in

How to install MinGW-w64 and MSYS2?

and I am currently trying to build some Win32 C programs. I first tried some simple programs and they seem to work; however, I ran into problems with the C abort function.

If I build the following program on Linux

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

int main(int argc, char *argv[]) {
  printf("bla bla bla\n");
  abort();
}

and later run it, I simply get the output

bla bla bla
Aborted

However, on Windows the output is

bla bla bla

This application has requested the Runtime to terminate it in an unusual
way. Please contact the application's support team for more information.

A message window also appears with the message

a.exe has stopped working -- A problem caused the program to stop working correctly. Windows will close the program and notify you if a solution is available.

Is this the way it is supposed to be? Anyway, I much prefer the Linux version.


回答1:


abort is the same as raise(SIGABRT).

If you don't catch the SIGABRT signal, the default OS handler is invoked, on Linux this is dumping core, causing the shell to write Aborted on standard error.

On Windows, it terminates and the message you saw is displayed, on standard error if console subsystem is used or in a standard message box if gui. This can be suppressed by the non-standard _set_abort_behavior.

If you want a uniform action across systems, you need to register a SIGABRT handler and do something yourself:

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

void handle_abort(int sig)
{
   // do something (e.g write to log)
   // don't let this handler return if you want to suppress defaut handler
}

int main(void)
{    
    signal(SIGABRT, handle_abort);

    abort();
}


来源:https://stackoverflow.com/questions/37019889/strange-behavior-of-c-abort-function-on-mingw-w64

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!