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!

  • 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. – NPE Jan 14 '15 at 18:53
  • @NPE that's what I was afraid of :s, currently I don't have the skills to fix the problem :/ –  Jan 14 '15 at 19:06
  • You should have the skills to write a bug report though! – Ulrich Eckhardt Apr 09 '15 at 05:56

2 Answers2

7

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://stackoverflow.com/a/10203062/439494

Community
  • 1
  • 1
Havok
  • 5,776
  • 1
  • 35
  • 44
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)
mkrieger1
  • 19,194
  • 5
  • 54
  • 65
where23
  • 483
  • 3
  • 9
  • 3
    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. – Matteo Ferla Jan 10 '20 at 10:52