How to handle child SIGFPE / SIGILL signals using subprocess and preexec_fn?

On Linux, I have an executable that I want to run through a Python script. The executable divides by zero and I cannot handle the signal from the subprocess. I've read and it seems that preexec_fn should handle SIGFPE, but no luck so far.

I am using Python 2.7

My code:

# b.py
import os
import subprocess
import signal
import sys

def pref_fun():
    signal.signal(signal.SIGFPE,foo)

def foo(signal,frame):
    print "Caught signal!"
    sys.exit(0)

sub = subprocess.Popen(["a.out"], preexec_fn=pref_fun)
sub.wait()
v = sub.returncode
print "value: ", v

      

and my child device:

a.c
#include <stdio.h>
#include <stdlib.h>
int main() {
    printf("Now dividing by zero\n");
    fflush(stdout);
    double x = 5;
    x= 5/0;
    printf("oh no\n");
    return 0;

}

      

The expected result is "Caught signal!" But I don't seem to understand.

+3


source to share


2 answers


I am afraid that we cannot do it this way. Although the signal handler was set in a split child after ./a.out

was exec()

ed, an image that has a signal handler, it has been replaced by the latter, so that there are no more handlers in the child. However, we can check if the child process was terminated by a signal using os.WIFSIGNALED(v)

, if True, we can use os.WTERMSIG(v)

to get what signal it was, after that we can do something in the parent.

However, I got very strange results from os.WTERMSIG(v)

on my machine and found that the real signal number seemed to be a negative value v

(I checked SIGSEGV

and SIGFPE

). Anyway, hope this helps :).

import os
import subprocess
import signal
import sys 

def pref_fun():
    signal.signal(signal.SIGFPE,foo)

def foo(signal,frame):
    print "Caught signal!"
    sys.exit(0)

sub = subprocess.Popen(["./a.out"], preexec_fn=pref_fun)
sub.wait()
v = sub.returncode
print "value: ", v
print os.WIFSIGNALED(v)
print "signal:", os.WTERMSIG(v)
print "SIGFPE", signal.SIGFPE    

      



which outputs:

Now dividing by zero
value:  -8
True
signal: 120
SIGFPE 8

      

+1


source


Make sure your Python is compiled with this configure option: --with-fpectl enable SIGFPE capture



0


source







All Articles