On Linux I have an executable I wish to run via Python script. The executable divides by zero, and I can’t seem to handle the signal from subprocess.
I read around and it seem that the preexec_fn should handle SIGFPE, but no luck so far.
I’m 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:
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 output is “Caught signal!”, but I don’t seem to get it.
I am afraid that we can’t do it in such way. Though the signal handler was installed in the forked child, after
./a.outwasexec()ed, the image which has the signal handler was replaced by the latter one — so there’s no handlers in the child process any more. Yet we can check whether the child process was terminated by a signal by usingos.WIFSIGNALED(v), if True, we can useos.WTERMSIG(v)to get which signal it was, after this, we can do something in parent.However, I got very odd results from
os.WTERMSIG(v)on my machine, and found that the real signal number seemed to be the negative ofv(I’d checkedSIGSEGVandSIGFPE), I don’t know whether if it is my machine’s issue, anyway, hope this helps :).which outputs: