I do not really write C, but sometimes I need to use software written in C.
For example, one recent test required Python to call into a shared library through ctypes. During testing, I found that a segmentation fault would sometimes occur, and once it did, the Python process crashed as well.
This kind of crash cannot be caught with a normal Python try block. Once it happens, the interpreter simply dies. Since the original crash in my real code was random and hard to reproduce, I looked up some basic examples and wrote a tiny test library that would always crash, so I could use it to evaluate possible workarounds.
Here is the C code:
1 | int fault(void) |
Save it as segfault.c, then compile it into a shared object:
1 | gcc -fPIC -shared -o ./segfault.so segfault.c |
Then call it from Python with ctypes:
1 | import ctypes |
Running the Python script produces:
Segmentation fault
After testing, I did not find any particularly elegant way to keep the Python interpreter itself alive after this kind of crash. In the end, I used subprocess to call a separate Python process, so the main program would survive even if the child process crashed.
If anyone has a better solution, I would genuinely love to hear it.