Is there a point to trapping “segfault”?

后端 未结 6 1703
时光说笑
时光说笑 2021-01-03 04:03

I know that, given enough context, one could hope to use constructively (i.e. recover) from a segfault condition.

But, is the effort worth it? If yes, in w

6条回答
  •  南方客
    南方客 (楼主)
    2021-01-03 04:33

    You can't really hope to recover from a segfault. You can detect that it happened, and dump out relevant application-specific state if possible, but you can't continue the process. This is because (amongst others)

    • The thread which failed cannot be continued, so your only options are longjmp or terminating the thread. Neither is safe in most cases.
    • Either way, you may leave a mutex / lock in a locked state which causes other threads to wait forever
    • Even if that doesn't happen, you may leak resources
    • Even if you don't do either of those things, the thread which segfaulted may have left the internal state of the application inconsistent when it failed. An inconsistent internal state could cause data errors or further bad behaviour subsequently which causes more problems than simply quitting

    So in general, there is no point in trapping it and doing anything EXCEPT terminating the process in a fairly abrupt fashion. There's no point in attempting to write (important) data back to disc, or continue to do other useful work. There is some point in dumping out state to logs- which many applications do - and then quitting.

    A possibly useful thing to do might be to exec() your own process, or have a watchdog process which restarts it in the case of a crash. (NB: exec does not always have well defined behaviour if your process has >1 thread)

提交回复
热议问题