using "try" to avoiding a segmentation fault
Asked Answered
F

2

7

Recently in one of my programs I got a segmentation fault problem. I managed to find the line that its is causing the problem but I haven't find the way of fixing it.

the line:

self.window_player.add(self.vlc)

where self.vlc is a widget and self.window_player is an empty Gtk.Window() created in glade.

The line is at the __init__ of my program, so actually this problem only happen when launching the program. The weird fact is that the error only appears like 1 of 10 times (of launching the program)

the error: Segmentation fault is the only output that I get from the terminal

So I tried:

while True:
    try:
        self.window_player.add(self.vlc)
        break
    except:
        print "segmentation"

The problem is that the segmentation fault don't seems to be excepted by the try!

Feeney answered 14/1, 2015 at 18:49 Comment(3)
In a nutshell, you can't handle a segfault using Python exception machinery. The clean solution would be to get to the bottom of the crash and fix it.Collbaith
@Collbaith that's what I was afraid of :s, currently I don't have the skills to fix the problem :/Feeney
You should have the skills to write a bug report though!Brownnose
S
8

Sorry, you can't handle it. A segfault is caused by memory corruption, reading or writing beyond boundaries of owned memory, double frees, and a few other.

You can found a few examples of issues that cause a segfault here:

https://gist.github.com/carlos-jenkins/8873932

The operating system will kill the offending program, you can't do much about it. Your only solution is to correct the root problem.

You can run a program using the tool Valgrind, it will allow you to find exactly where the problem is:

http://valgrind.org/

On Ubuntu, just sudo apt-get install valgrind and then valgrind <program cmd> will launch the program. This offcourse will be a lot slower, but will identify the problem most of the time.

Side note: Technically you can catch a SIGSEV signal by registering a callback for this signal. But you shouldn't. See this answer for more information:

https://mcmap.net/q/21342/-segmentation-fault-handling

Spacious answered 15/1, 2015 at 0:51 Comment(0)
B
3

You can handle the signal SIGSEGV with the function you specified, as following

from signal import signal, SIGSEGV

def handler(sigNum, frame):
    print("handle signal", sigNum)

signal(SIGSEGV, handler)
Beamy answered 25/11, 2019 at 8:19 Comment(1)
The top answer states this is generally dangerous and I wanted to expand on that (for any reader). The signal is caught in the main thread, so if there are multiple treads or cores, the code will likely just hang awaiting offending thread and finding the culprit is not trivial as it may have involved memory leakage etc. so fixing the source is better. NB. catching SIGINT (someone asked it to die) this way is totally fine.Heft

© 2022 - 2024 — McMap. All rights reserved.