/* Signal module -- many thanks to Lance Ellinghaus *//* XXX Signals should be recorded per thread, now we have thread state. */#include "Python.h"#include "intrcheck.h"#ifdef MS_WIN32#include <process.h>#endif#ifdef HAVE_UNISTD_H#include <unistd.h>#endif#include <signal.h>#ifndef SIG_ERR#define SIG_ERR ((PyOS_sighandler_t)(-1))#endif#if defined(PYOS_OS2)#define NSIG 12#include <process.h>#endif#ifndef NSIG# if defined(_NSIG)# define NSIG _NSIG /* For BSD/SysV */# elif defined(_SIGMAX)# define NSIG (_SIGMAX + 1) /* For QNX */# elif defined(SIGMAX)# define NSIG (SIGMAX + 1) /* For djgpp */# else# define NSIG 64 /* Use a reasonable default value */# endif#endif/* NOTES ON THE INTERACTION BETWEEN SIGNALS AND THREADS When threads are supported, we want the following semantics: - only the main thread can set a signal handler - any thread can get a signal handler - signals are only delivered to the main thread I.e. we don't support "synchronous signals" like SIGFPE (catching this doesn't make much sense in Python anyway) nor do we support signals as a means of inter-thread communication, since not all thread implementations support that (at least our thread library doesn't). We still have the problem that in some implementations signals generated by the keyboard (e.g. SIGINT) are delivered to all threads (e.g. SGI), while in others (e.g. Solaris) such signals are delivered to one random thread (an intermediate possibility would be to deliver it to the main thread -- POSIX?). For now, we have a working implementation that works in all three cases -- the handler ignores signals if getpid() isn't the same as in the main thread. XXX This is a hack. GNU pth is a user-space threading library, and as such, all threads run within the same process. In this case, if the currently running thread is not the main_thread, send the signal to the main_thread.*/#ifdef WITH_THREAD#include <sys/types.h> /* For pid_t */#include "pythread.h"staticlongmain_thread;staticpid_tmain_pid;#endifstaticstruct{inttripped;PyObject*func;}Handlers[NSIG];staticintis_tripped=0;/* Speed up sigcheck() when none tripped */staticPyObject*DefaultHandler;staticPyObject*IgnoreHandler;staticPyObject*IntHandler;/* On Solaris 8, gcc will produce a warning that the function declaration is not a prototype. This is caused by the definition of SIG_DFL as (void (*)())0; the correct declaration would have been (void (*)(int))0. */staticPyOS_sighandler_told_siginthandler=SIG_DFL;staticPyObject*signal_default_int_handler(PyObject*self,PyObject*args){PyErr_SetNone(PyExc_KeyboardInterrupt);returnNULL;}staticchardefault_int_handler_doc[]="default_int_handler(...)\n\\n\The default handler for SIGINT instated by Python.\n\It raises KeyboardInterrupt.";staticintchecksignals_witharg(void*unused){returnPyErr_CheckSignals();}staticvoidsignal_handler(intsig_num){#ifdef WITH_THREAD#ifdef WITH_PTHif(PyThread_get_thread_ident()!=main_thread){pth_raise(*(pth_t*)main_thread,sig_num);return;}#endif/* See NOTES section above */if(getpid()==main_pid){#endifis_tripped++;Handlers[sig_num].tripped=1;Py_AddPendingCall(checksignals_witharg,NULL);#ifdef WITH_THREAD}#endif#ifdef SIGCHLDif(sig_num==SIGCHLD){/* To avoid infinite recursion, this signal remains reset until explicit re-instated. Don't clear the 'func' field as it is our pointer to the Python handler... */return;}#endif#ifdef HAVE_SIGINTERRUPTsiginterrupt(sig_num,1);#endifPyOS_setsig(sig_num,signal_handler);}#ifdef HAVE_ALARMstaticPyObject*signal_alarm(PyObject*self,PyObject*args){intt;if(!PyArg_Parse(args,"i",&t))returnNULL;/* alarm() returns the number of seconds remaining */returnPyInt_FromLong(alarm(t));}staticcharalarm_doc[]="alarm(seconds)\n\\n\Arrange for SIGALRM to arrive after the given number of seconds.";#endif#ifdef HAVE_PAUSEstaticPyObject*signal_pause(PyObject*self,PyObject*args){if(!PyArg_NoArgs(args))returnNULL;Py_BEGIN_ALLOW_THREADS(void)pause();Py_END_ALLOW_THREADS/* make sure that any exceptions that got raised are propagated * back into Python */if(PyErr_CheckSignals())returnNULL;Py_INCREF(Py_None);returnPy_None;}staticcharpause_doc[]="pause()\n\\n\Wait until a signal arrives.";#endifstaticPyObject*signal_signal(PyObject*self,PyObject*args){PyObject*obj;intsig_num;PyObject*old_handler;void(*func)(int);if(!PyArg_Parse(args,"(iO)",&sig_num,&obj))returnNULL;#ifdef WITH_THREADif(PyThread_get_thread_ident()!=main_thread){PyErr_SetString(PyExc_ValueError,"signal only works in main thread");returnNULL;}#endifif(sig_num<1||sig_num>=NSIG){PyErr_SetString(PyExc_ValueError,"signal number out of range");returnNULL;}if(obj==IgnoreHandler)func=SIG_IGN;elseif(obj==DefaultHandler)func=SIG_DFL;elseif(!PyCallable_Check(obj)){PyErr_SetString(PyExc_TypeError,"signal handler must be signal.SIG_IGN, signal.SIG_DFL, or a callable object");returnNULL;}elsefunc=signal_handler;#ifdef HAVE_SIGINTERRUPTsiginterrupt(sig_num,1);#endifif(PyOS_setsig(sig_num,func)==SIG_ERR){PyErr_SetFromErrno(PyExc_RuntimeError);returnNULL;}old_handler=Handlers[sig_num].func;Handlers[sig_num].tripped=0;Py_INCREF(obj);Handlers[sig_num].func=obj;returnold_handler;}staticcharsignal_doc[]="signal(sig, action) -> action\n\\n\Set the action for the given signal. The action can be SIG_DFL,\n\SIG_IGN, or a callable Python object. The previous action is\n\returned. See getsignal() for possible return values.\n\\n\*** IMPORTANT NOTICE ***\n\A signal handler function is called with two arguments:\n\the first is the signal number, the second is the interrupted stack frame.";staticPyObject*signal_getsignal(PyObject*self,PyObject*args){intsig_num;PyObject*old_handler;if(!PyArg_Parse(args,"i",&sig_num))returnNULL;if(sig_num<1||sig_num>=NSIG){PyErr_SetString(PyExc_ValueError,"signal number out of range");returnNULL;}old_handler=Handlers[sig_num].func;Py_INCREF(old_handler);returnold_handler;}staticchargetsignal_doc[]="getsignal(sig) -> action\n\\n\Return the current action for the given signal. The return value can be:\n\SIG_IGN -- if the signal is being ignored\n\SIG_DFL -- if the default action for the signal is in effect\n\None -- if an unknown handler is in effect\n\anything else -- the callable Python object used as a handler\n\";/* List of functions defined in the module */staticPyMethodDefsignal_methods[]={#ifdef HAVE_ALARM{"alarm",signal_alarm,METH_OLDARGS,alarm_doc},#endif{"signal",signal_signal,METH_OLDARGS,signal_doc},{"getsignal",signal_getsignal,METH_OLDARGS,getsignal_doc},#ifdef HAVE_PAUSE{"pause",signal_pause,METH_OLDARGS,pause_doc},#endif{"default_int_handler",signal_default_int_handler,METH_OLDARGS,default_int_handler_doc},{NULL,NULL}/* sentinel */};staticcharmodule_doc[]="This module provides mechanisms to use signal handlers in Python.\n\\n\Functions:\n\\n\alarm() -- cause SIGALRM after a specified time [Unix only]\n\signal() -- set the action for a given signal\n\getsignal() -- get the signal action for a given signal\n\pause() -- wait until a signal arrives [Unix only]\n\default_int_handler() -- default SIGINT handler\n\\n\Constants:\n\\n\SIG_DFL -- used to refer to the system default handler\n\SIG_IGN -- used to ignore the signal\n\NSIG -- number of defined signals\n\\n\SIGINT, SIGTERM, etc. -- signal numbers\n\\n\*** IMPORTANT NOTICE ***\n\A signal handler function is called with two arguments:\n\the first is the signal number, the second is the interrupted stack frame.";DL_EXPORT(void)initsignal(void){PyObject*m,*d,*x;inti;#ifdef WITH_THREADmain_thread=PyThread_get_thread_ident();main_pid=getpid();#endif/* Create the module and add the functions */m=Py_InitModule3("signal",signal_methods,module_doc);/* Add some symbolic constants to the module */d=PyModule_GetDict(m);x=DefaultHandler=PyLong_FromVoidPtr((void*)SIG_DFL);if(!x||PyDict_SetItemString(d,"SIG_DFL",x)<0)gotofinally;x=IgnoreHandler=PyLong_FromVoidPtr((void*)SIG_IGN);if(!x||PyDict_SetItemString(d,"SIG_IGN",x)<0)gotofinally;x=PyInt_FromLong((long)NSIG);if(!x||PyDict_SetItemString(d,"NSIG",x)<0)gotofinally;Py_DECREF(x);x=IntHandler=PyDict_GetItemString(d,"default_int_handler");if(!x)gotofinally;Py_INCREF(IntHandler);Handlers[0].tripped=0;for(i=1;i<NSIG;i++){void(*t)(int);t=PyOS_getsig(i);Handlers[i].tripped=0;if(t==SIG_DFL)Handlers[i].func=DefaultHandler;elseif(t==SIG_IGN)Handlers[i].func=IgnoreHandler;elseHandlers[i].func=Py_None;/* None of our business */Py_INCREF(Handlers[i].func);}if(Handlers[SIGINT].func==DefaultHandler){/* Install default int handler */Py_INCREF(IntHandler);Py_DECREF(Handlers[SIGINT].func);Handlers[SIGINT].func=IntHandler;old_siginthandler=PyOS_setsig(SIGINT,&signal_handler);}#ifdef SIGHUPx=PyInt_FromLong(SIGHUP);PyDict_SetItemString(d,"SIGHUP",x);Py_XDECREF(x);#endif#ifdef SIGINTx=PyInt_FromLong(SIGINT);PyDict_SetItemString(d,"SIGINT",x);Py_XDECREF(x);#endif#ifdef SIGQUITx=PyInt_FromLong(SIGQUIT);PyDict_SetItemString(d,"SIGQUIT",x);Py_XDECREF(x);#endif#ifdef SIGILLx=PyInt_FromLong(SIGILL);PyDict_SetItemString(d,"SIGILL",x);Py_XDECREF(x);#endif#ifdef SIGTRAPx=PyInt_FromLong(SIGTRAP);PyDict_SetItemString(d,"SIGTRAP",x);Py_XDECREF(x);#endif#ifdef SIGIOTx=PyInt_FromLong(SIGIOT);PyDict_SetItemString(d,"SIGIOT",x);Py_XDECREF(x);#endif#ifdef SIGABRTx=PyInt_FromLong(SIGABRT);PyDict_SetItemString(d,"SIGABRT",x);Py_XDECREF(x);#endif#ifdef SIGEMTx=PyInt_FromLong(SIGEMT);PyDict_SetItemString(d,"SIGEMT",x);Py_XDECREF(x);#endif#ifdef SIGFPEx=PyInt_FromLong(SIGFPE);PyDict_SetItemString(d,"SIGFPE",x);Py_XDECREF(x);#endif#ifdef SIGKILLx=PyInt_FromLong(SIGKILL);PyDict_SetItemString(d,"SIGKILL",x);Py_XDECREF(x);#endif#ifdef SIGBUSx=PyInt_FromLong(SIGBUS);PyDict_SetItemString(d,"SIGBUS",x);Py_XDECREF(x);#endif#ifdef SIGSEGVx=PyInt_FromLong(SIGSEGV);PyDict_SetItemString(d,"SIGSEGV",x);Py_XDECREF(x);#endif#ifdef SIGSYSx=PyInt_FromLong(SIGSYS);PyDict_SetItemString(d,"SIGSYS",x);Py_XDECREF(x);#endif#ifdef SIGPIPEx=PyInt_FromLong(SIGPIPE);PyDict_SetItemString(d,"SIGPIPE",x);Py_XDECREF(x);#endif#ifdef SIGALRMx=PyInt_FromLong(SIGALRM);PyDict_SetItemString(d,"SIGALRM",x);Py_XDECREF(x);#endif#ifdef SIGTERMx=PyInt_FromLong(SIGTERM);PyDict_SetItemString(d,"SIGTERM",x);Py_XDECREF(x);#endif#ifdef SIGUSR1x=PyInt_FromLong(SIGUSR1);PyDict_SetItemString(d,"SIGUSR1",x);Py_XDECREF(x);#endif#ifdef SIGUSR2x=PyInt_FromLong(SIGUSR2);PyDict_SetItemString(d,"SIGUSR2",x);Py_XDECREF(x);#endif#ifdef SIGCLDx=PyInt_FromLong(SIGCLD);PyDict_SetItemString(d,"SIGCLD",x);Py_XDECREF(x);#endif#ifdef SIGCHLDx=PyInt_FromLong(SIGCHLD);PyDict_SetItemString(d,"SIGCHLD",x);Py_XDECREF(x);#endif#ifdef SIGPWRx=PyInt_FromLong(SIGPWR);PyDict_SetItemString(d,"SIGPWR",x);Py_XDECREF(x);#endif#ifdef SIGIOx=PyInt_FromLong(SIGIO);PyDict_SetItemString(d,"SIGIO",x);Py_XDECREF(x);#endif#ifdef SIGURGx=PyInt_FromLong(SIGURG);PyDict_SetItemString(d,"SIGURG",x);Py_XDECREF(x);#endif#ifdef SIGWINCHx=PyInt_FromLong(SIGWINCH);PyDict_SetItemString(d,"SIGWINCH",x);Py_XDECREF(x);#endif#ifdef SIGPOLLx=PyInt_FromLong(SIGPOLL);PyDict_SetItemString(d,"SIGPOLL",x);Py_XDECREF(x);#endif#ifdef SIGSTOPx=PyInt_FromLong(SIGSTOP);PyDict_SetItemString(d,"SIGSTOP",x);Py_XDECREF(x);#endif#ifdef SIGTSTPx=PyInt_FromLong(SIGTSTP);PyDict_SetItemString(d,"SIGTSTP",x);Py_XDECREF(x);#endif#ifdef SIGCONTx=PyInt_FromLong(SIGCONT);PyDict_SetItemString(d,"SIGCONT",x);Py_XDECREF(x);#endif#ifdef SIGTTINx=PyInt_FromLong(SIGTTIN);PyDict_SetItemString(d,"SIGTTIN",x);Py_XDECREF(x);#endif#ifdef SIGTTOUx=PyInt_FromLong(SIGTTOU);PyDict_SetItemString(d,"SIGTTOU",x);Py_XDECREF(x);#endif#ifdef SIGVTALRMx=PyInt_FromLong(SIGVTALRM);PyDict_SetItemString(d,"SIGVTALRM",x);Py_XDECREF(x);#endif#ifdef SIGPROFx=PyInt_FromLong(SIGPROF);PyDict_SetItemString(d,"SIGPROF",x);Py_XDECREF(x);#endif#ifdef SIGXCPUx=PyInt_FromLong(SIGXCPU);PyDict_SetItemString(d,"SIGXCPU",x);Py_XDECREF(x);#endif#ifdef SIGXFSZx=PyInt_FromLong(SIGXFSZ);PyDict_SetItemString(d,"SIGXFSZ",x);Py_XDECREF(x);#endifif(!PyErr_Occurred())return;/* Check for errors */finally:return;}staticvoidfinisignal(void){inti;PyObject*func;PyOS_setsig(SIGINT,old_siginthandler);old_siginthandler=SIG_DFL;for(i=1;i<NSIG;i++){func=Handlers[i].func;Handlers[i].tripped=0;Handlers[i].func=NULL;if(i!=SIGINT&&func!=NULL&&func!=Py_None&&func!=DefaultHandler&&func!=IgnoreHandler)PyOS_setsig(i,SIG_DFL);Py_XDECREF(func);}Py_XDECREF(IntHandler);IntHandler=NULL;Py_XDECREF(DefaultHandler);DefaultHandler=NULL;Py_XDECREF(IgnoreHandler);IgnoreHandler=NULL;}/* Declared in pyerrors.h */intPyErr_CheckSignals(void){inti;PyObject*f;if(!is_tripped)return0;#ifdef WITH_THREADif(PyThread_get_thread_ident()!=main_thread)return0;#endifif(!(f=PyEval_GetFrame()))f=Py_None;for(i=1;i<NSIG;i++){if(Handlers[i].tripped){PyObject*result=NULL;PyObject*arglist=Py_BuildValue("(iO)",i,f);Handlers[i].tripped=0;if(arglist){result=PyEval_CallObject(Handlers[i].func,arglist);Py_DECREF(arglist);}if(!result)return-1;Py_DECREF(result);}}is_tripped=0;return0;}/* Replacements for intrcheck.c functionality * Declared in pyerrors.h */voidPyErr_SetInterrupt(void){is_tripped++;Handlers[SIGINT].tripped=1;Py_AddPendingCall((int(*)(void*))PyErr_CheckSignals,NULL);}voidPyOS_InitInterrupts(void){initsignal();_PyImport_FixupExtension("signal","signal");}voidPyOS_FiniInterrupts(void){finisignal();}intPyOS_InterruptOccurred(void){if(Handlers[SIGINT].tripped){#ifdef WITH_THREADif(PyThread_get_thread_ident()!=main_thread)return0;#endifHandlers[SIGINT].tripped=0;return1;}return0;}voidPyOS_AfterFork(void){#ifdef WITH_THREADPyEval_ReInitThreads();main_thread=PyThread_get_thread_ident();main_pid=getpid();#endif}