When signal handler is not called when segment fault occurs?

允我心安 提交于 2021-02-10 06:11:47

问题


Below is the operation method of my program, and there was a case where the registered handler was not called when the program was terminated due to the occurrence of a segment fault.

Is there a case where the registered handler can be terminated without being called when a segment fault occurs?

  1. When initializing program A, register handler through signal() function.( SIGSEGV, SIGABRT, SIGFPE, SIGTERM )
  2. fork() -> waitpid() for program A in program B
  3. Aging
  4. Segment Fault occurs due to unknown reason in A program
  5. The waitpid status of the B program is passed to segment fault(11).
  6. The handler registered in A program is not called and ends.

回答1:


A well-formed, well-defined C++ application will never result in a segfault.

A segfault is a result of undefined behavior; but when undefined behavior occurs, by definition you can not expect any specific result or behavior. You have no expectation that a seg fault will occur as a result of undefined behavior, and even if occurs you cannot expect that the SIGSEGV handler will produce any expected result, at all.

The number of examples that can be given has no limit. Let's say, for example, the segfault handler attempts to remove a temporary file that gets created before the segfault. Too bad, the undefined behavior resulted in corrupting the buffer that stored the name of the temporary file, in addition to causing a segfault. The segfault handler fails. Or, even better, the corrupted filename buffer happened to match the name of another file, and it gets deleted by mistake. If you were running as root, and the corrupted filename buffer by chance ended up containing "/bin/bash", you've just turned your machine into an unbootable brick.

Many other possibilities can also happen, limited only to one's imagination. You did not describe what your sigsegv handler attempts to do, but it doesn't matter. Whatever it tries to do it has no guarantee of always working. It is too late, by the time it gets invoked undefined behavior already happened, and you have no expectation of anything happening, from that point on.

So, whatever the segfault handler attempts to do, it has no guarantee, whatsoever that it can accomplish its task. By the time the segfault handler gets invoked the state of the rest of the program, and its data, is undefined and unspecified.

Which is why when there's a bug that results in a segfault, the correct way to handle it is to figure out the reason for the segfault, find the bug and fix it. Any attempt to remedy the situation by catching the signal and the cleaning up is, at best, a crapshoot has no guarantee of always succeeding.



来源:https://stackoverflow.com/questions/63770819/when-signal-handler-is-not-called-when-segment-fault-occurs

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