diff -r 89665cc05592 -r 7549df84dd2c Doc/c-api/exceptions.rst --- a/Doc/c-api/exceptions.rst Tue Jul 22 21:29:52 2014 +0100 +++ b/Doc/c-api/exceptions.rst Wed Jul 23 00:41:11 2014 +0200 @@ -443,9 +443,10 @@ in various ways. There is a separate er .. c:function:: int PySignal_SetWakeupFd(int fd) - This utility function specifies a file descriptor to which a ``'\0'`` byte will - be written whenever a signal is received. It returns the previous such file - descriptor. The value ``-1`` disables the feature; this is the initial state. + This utility function specifies a file descriptor to which the signal number + is written as a single byte whenever a signal is received. It returns + the previous such file descriptor. + The value ``-1`` disables the feature; this is the initial state. This is equivalent to :func:`signal.set_wakeup_fd` in Python, but without any error checking. *fd* should be a valid file descriptor. The function should only be called from the main thread. diff -r 89665cc05592 -r 7549df84dd2c Doc/library/signal.rst --- a/Doc/library/signal.rst Tue Jul 22 21:29:52 2014 +0100 +++ b/Doc/library/signal.rst Wed Jul 23 00:41:11 2014 +0200 @@ -318,6 +318,9 @@ The :mod:`signal` module defines the fol attempting to call it from other threads will cause a :exc:`ValueError` exception to be raised. + .. versionchanged:: 3.5 + Sockets are now also supported on Windows. + .. function:: siginterrupt(signalnum, flag) diff -r 89665cc05592 -r 7549df84dd2c Lib/test/test_signal.py --- a/Lib/test/test_signal.py Tue Jul 22 21:29:52 2014 +0100 +++ b/Lib/test/test_signal.py Wed Jul 23 00:41:11 2014 +0200 @@ -6,6 +6,7 @@ import gc import pickle import select import signal +import socket import struct import subprocess import traceback @@ -441,6 +442,90 @@ class WakeupSignalTests(unittest.TestCas """, signal.SIGUSR1, signal.SIGUSR2, ordered=False) +@unittest.skipUnless(hasattr(socket, 'socketpair'), 'need socket.socketpair') +class WakeupSocketSignalTests(unittest.TestCase): + + @unittest.skipIf(_testcapi is None, 'need _testcapi') + def test_socket(self): + # use a subprocess to have only one thread + code = """if 1: + import signal + import socket + import struct + import _testcapi + + signum = signal.SIGINT + signals = (signum,) + + def handler(signum, frame): + pass + + signal.signal(signum, handler) + + read, write = socket.socketpair() + read.setblocking(False) + write.setblocking(False) + signal.set_wakeup_fd(write.fileno()) + + _testcapi.raise_signal(signum) + + data = read.recv(1) + if not data: + raise Exception("no signum written") + raised = struct.unpack('B', data) + if raised != signals: + raise Exception("%r != %r" % (raised, signals)) + + read.close() + write.close() + """ + + assert_python_ok('-c', code) + + @unittest.skipIf(_testcapi is None, 'need _testcapi') + def test_send_error(self): + # Use a subprocess to have only one thread. + if os.name == 'nt': + action = 'send' + else: + action = 'write' + code = """if 1: + import errno + import signal + import socket + import sys + import time + import _testcapi + from test.support import captured_stderr + + signum = signal.SIGINT + + def handler(signum, frame): + pass + + signal.signal(signum, handler) + + read, write = socket.socketpair() + read.setblocking(False) + write.setblocking(False) + + signal.set_wakeup_fd(write.fileno()) + + # Close sockets: send() will fail + read.close() + write.close() + + with captured_stderr() as err: + _testcapi.raise_signal(signum) + + err = err.getvalue() + if ('Exception ignored when trying to {action} to the signal wakeup fd' + not in err): + raise AssertionError(err) + """.format(action=action) + assert_python_ok('-c', code) + + @unittest.skipIf(sys.platform == "win32", "Not valid on Windows") class SiginterruptTest(unittest.TestCase): @@ -990,6 +1075,7 @@ def test_main(): try: support.run_unittest(GenericTests, PosixTests, InterProcessSignalTests, WakeupFDTests, WakeupSignalTests, + WakeupSocketSignalTests, SiginterruptTest, ItimerTest, WindowsSignalTests, PendingSignalsTests) finally: diff -r 89665cc05592 -r 7549df84dd2c Modules/signalmodule.c --- a/Modules/signalmodule.c Tue Jul 22 21:29:52 2014 +0100 +++ b/Modules/signalmodule.c Wed Jul 23 00:41:11 2014 +0200 @@ -4,6 +4,9 @@ /* XXX Signals should be recorded per thread, now we have thread state. */ #include "Python.h" +#ifdef MS_WINDOWS +#include "socketmodule.h" /* needed for SOCKET_T */ +#endif #ifndef MS_WINDOWS #include "posixmodule.h" #endif @@ -87,7 +90,19 @@ static volatile struct { PyObject *func; } Handlers[NSIG]; +#define INVALID_FD -1 + +#ifdef MS_WINDOWS +static volatile struct { + SOCKET_T fd; + int use_send; + int send_err_set; + int send_errno; + int send_win_error; +} wakeup = {INVALID_FD, 0, 0}; +#else static volatile sig_atomic_t wakeup_fd = -1; +#endif /* Speed up sigcheck() when none tripped */ static volatile sig_atomic_t is_tripped = 0; @@ -172,7 +187,7 @@ checksignals_witharg(void * unused) } static int -report_wakeup_error(void *data) +report_wakeup_write_error(void *data) { int save_errno = errno; errno = (int) (Py_intptr_t) data; @@ -184,25 +199,84 @@ report_wakeup_error(void *data) return 0; } +#ifdef MS_WINDOWS +static int +report_wakeup_send_error(void* Py_UNUSED(data)) +{ + PyObject *res; + + if (wakeup.send_win_error) { + /* PyErr_SetExcFromWindowsErr() invokes FormatMessage() which + recognizes the error codes used by both GetLastError() and + WSAGetLastError */ + res = PyErr_SetExcFromWindowsErr(PyExc_OSError, wakeup.send_win_error); + } + else { + int save_errno = errno; + errno = wakeup.send_errno; + res = PyErr_SetFromErrno(PyExc_OSError); + errno = save_errno; + } + assert(res == NULL); + + wakeup.send_err_set = 0; + + PySys_WriteStderr("Exception ignored when trying to send to the " + "signal wakeup fd:\n"); + PyErr_WriteUnraisable(NULL); + + return 0; +} +#endif + static void trip_signal(int sig_num) { unsigned char byte; - int rc = 0; +#ifdef MS_WINDOWS + SOCKET_T fd = wakeup.fd; +#else + int fd = wakeup_fd; +#endif + Py_ssize_t rc; Handlers[sig_num].tripped = 1; - if (wakeup_fd != -1) { - byte = (unsigned char)sig_num; - while ((rc = write(wakeup_fd, &byte, 1)) == -1 && errno == EINTR); - if (rc == -1) - Py_AddPendingCall(report_wakeup_error, (void *) (Py_intptr_t) errno); + + if (fd != INVALID_FD) { +#ifdef MS_WINDOWS + if (wakeup.use_send) { + byte = (unsigned char)sig_num; + do { + rc = send(fd, &byte, 1, 0); + } while (rc < 0 && errno == EINTR); + /* we only have a storage for one error in the wakeup structure */ + if (rc < 0 && !wakeup.send_err_set) { + wakeup.send_err_set = 1; + wakeup.send_errno = errno; + wakeup.send_win_error = GetLastError(); + Py_AddPendingCall(report_wakeup_send_error, + (void *)(Py_intptr_t)errno); + } + } + else +#endif + { + byte = (unsigned char)sig_num; + do { + rc = write(fd, &byte, 1); + } while (rc < 0 && errno == EINTR); + if (rc < 0) + Py_AddPendingCall(report_wakeup_write_error, + (void *)(Py_intptr_t)errno); + } } - if (is_tripped) - return; - /* Set is_tripped after setting .tripped, as it gets - cleared in PyErr_CheckSignals() before .tripped. */ - is_tripped = 1; - Py_AddPendingCall(checksignals_witharg, NULL); + + if (!is_tripped) { + /* Set is_tripped after setting .tripped, as it gets + cleared in PyErr_CheckSignals() before .tripped. */ + is_tripped = 1; + Py_AddPendingCall(checksignals_witharg, NULL); + } } static void @@ -426,10 +500,29 @@ signal_siginterrupt(PyObject *self, PyOb static PyObject * signal_set_wakeup_fd(PyObject *self, PyObject *args) { - struct stat buf; +#ifdef MS_WINDOWS + PyObject *fdobj; + SOCKET_T fd, old_fd; + int res; + int res_size = sizeof res; + PyObject *mod; + int is_socket; + struct stat st; + + if (!PyArg_ParseTuple(args, "O:set_wakeup_fd", &fdobj)) + return NULL; + + fd = PyLong_AsSocket_t(fdobj); + if (fd == (SOCKET_T)(-1) && PyErr_Occurred()) + return NULL; +#else int fd, old_fd; + struct stat st; + if (!PyArg_ParseTuple(args, "i:set_wakeup_fd", &fd)) return NULL; +#endif + #ifdef WITH_THREAD if (PyThread_get_thread_ident() != main_thread) { PyErr_SetString(PyExc_ValueError, @@ -438,28 +531,70 @@ signal_set_wakeup_fd(PyObject *self, PyO } #endif +#ifdef MS_WINDOWS + is_socket = 0; + if (fd != (SOCKET_T)INVALID_FD) { + /* Import the _socket module to call WSAStartup() */ + mod = PyImport_ImportModuleNoBlock("_socket"); + if (mod == NULL) + return NULL; + Py_DECREF(mod); + + /* use getsockopt(fd) fails with the WSAENOTSOCK Windows error + if fd is not a socket handler */ + if (getsockopt(fd, SOL_SOCKET, SO_ERROR, + (char *)&res, &res_size) != 0) { + if (WSAGetLastError() != WSAENOTSOCK) { + PyErr_SetExcFromWindowsErr(PyExc_OSError, WSAGetLastError()); + return NULL; + } + + if (!_PyVerify_fd(fd)) { + PyErr_SetString(PyExc_ValueError, "invalid fd"); + return NULL; + } + + if (fstat(fd, &st) != 0) { + PyErr_SetFromErrno(PyExc_OSError); + return NULL; + } + + is_socket = 0; + } + else { + is_socket = 1; + } + } + + old_fd = wakeup.fd; + wakeup.fd = fd; + wakeup.use_send = is_socket; + + if (old_fd != (SOCKET_T)INVALID_FD) + return PyLong_FromSocket_t(old_fd); + else + return PyLong_FromLong(-1); +#else if (fd != -1) { - if (!_PyVerify_fd(fd)) { - PyErr_SetString(PyExc_ValueError, "invalid fd"); + if (fstat(fd, &st) != 0) { + PyErr_SetFromErrno(PyExc_OSError); return NULL; } - - if (fstat(fd, &buf) != 0) - return PyErr_SetFromErrno(PyExc_OSError); } old_fd = wakeup_fd; wakeup_fd = fd; return PyLong_FromLong(old_fd); +#endif } PyDoc_STRVAR(set_wakeup_fd_doc, "set_wakeup_fd(fd) -> fd\n\ \n\ -Sets the fd to be written to (with '\\0') when a signal\n\ +Sets the fd to be written to (with the signal number) when a signal\n\ comes in. A library can use this to wakeup select or poll.\n\ -The previous fd is returned.\n\ +The previous fd or -1 is returned.\n\ \n\ The fd must be non-blocking."); @@ -467,10 +602,29 @@ The fd must be non-blocking."); int PySignal_SetWakeupFd(int fd) { - int old_fd = wakeup_fd; + int old_fd; +#ifdef MS_WINDOWS + SOCKET_T new_fd; + + if (fd >= 0) + new_fd = (SOCKET_T)fd; + else + new_fd = (SOCKET_T)INVALID_FD; + + if (!wakeup.use_send) + old_fd = wakeup.fd; + else + old_fd = -1; + + wakeup.use_send = 0; + wakeup.fd = new_fd; +#else if (fd < 0) fd = -1; + + old_fd = wakeup_fd; wakeup_fd = fd; +#endif return old_fd; } diff -r 89665cc05592 -r 7549df84dd2c PCbuild/pythoncore.vcxproj --- a/PCbuild/pythoncore.vcxproj Tue Jul 22 21:29:52 2014 +0100 +++ b/PCbuild/pythoncore.vcxproj Wed Jul 23 00:41:11 2014 +0200 @@ -176,7 +176,7 @@ "$(SolutionDir)make_buildinfo.exe" Release "$(IntDir)\" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) $(OutDir)$(PyDllName).dll libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 @@ -212,7 +212,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Release "$(IntDir)\" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 @@ -247,7 +247,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 @@ -285,7 +285,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Debug "$(IntDir)" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 @@ -317,7 +317,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Release "$(IntDir)\" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) $(OutDir)$(PyDllName).dll libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 @@ -353,7 +353,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Release "$(IntDir)\" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 MachineX64 @@ -386,7 +386,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Release "$(IntDir)\" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) $(OutDir)$(PyDllName).dll libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 @@ -422,7 +422,7 @@ IF %ERRORLEVEL% NEQ 0 ( "$(SolutionDir)make_buildinfo.exe" Release "$(IntDir)\" - $(IntDir)getbuildinfo.o;%(AdditionalDependencies) + $(IntDir)getbuildinfo.o;ws2_32.lib;%(AdditionalDependencies) libc;%(IgnoreSpecificDefaultLibraries) 0x1e000000 MachineX64