Skip to content

Commit 4702336

Browse files
committed
Issue python#1677: Handle better a race condition between the interactive interpreter and
the Ctrl-C signal handler on Windows
1 parent d07de40 commit 4702336

1 file changed

Lines changed: 16 additions & 23 deletions

File tree

‎Parser/myreadline.c‎

Lines changed: 16 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -40,6 +40,7 @@ static int
4040
my_fgets(char *buf, int len, FILE *fp)
4141
{
4242
char *p;
43+
int i;
4344
while (1) {
4445
if (PyOS_InputHook != NULL)
4546
(void)(PyOS_InputHook)();
@@ -49,32 +50,24 @@ my_fgets(char *buf, int len, FILE *fp)
4950
if (p != NULL)
5051
return 0; /* No error */
5152
#ifdef MS_WINDOWS
52-
/* In the case of a Ctrl+C or some other external event
53-
interrupting the operation:
54-
Win2k/NT: ERROR_OPERATION_ABORTED is the most recent Win32
55-
error code (and feof() returns TRUE).
56-
Win9x: Ctrl+C seems to have no effect on fgets() returning
57-
early - the signal handler is called, but the fgets()
58-
only returns "normally" (ie, when Enter hit or feof())
53+
/* Ctrl-C anywhere on the line or Ctrl-Z if the only character
54+
on a line will set ERROR_OPERATION_ABORTED. Under normal
55+
circumstances Ctrl-C will also have caused the SIGINT handler
56+
to fire. This signal fires in another thread and is not
57+
guaranteed to have occurred before this point in the code.
58+
59+
Therefore: check in a small loop to see if the trigger has
60+
fired, in which case assume this is a Ctrl-C event. If it
61+
hasn't fired within 10ms assume that this is a Ctrl-Z on its
62+
own or that the signal isn't going to fire for some other
63+
reason and drop through to check for EOF.
5964
*/
6065
if (GetLastError()==ERROR_OPERATION_ABORTED) {
61-
/* Signals come asynchronously, so we sleep a brief
62-
moment before checking if the handler has been
63-
triggered (we cant just return 1 before the
64-
signal handler has been called, as the later
65-
signal may be treated as a separate interrupt).
66-
*/
67-
Sleep(1);
68-
if (PyOS_InterruptOccurred()) {
69-
return 1; /* Interrupt */
66+
for (i = 0; i < 10; i++) {
67+
if (PyOS_InterruptOccurred())
68+
return 1;
69+
Sleep(1);
7070
}
71-
/* Either the sleep wasn't long enough (need a
72-
short loop retrying?) or not interrupted at all
73-
(in which case we should revisit the whole thing!)
74-
Logging some warning would be nice. assert is not
75-
viable as under the debugger, the various dialogs
76-
mean the condition is not true.
77-
*/
7871
}
7972
#endif /* MS_WINDOWS */
8073
if (feof(fp)) {

0 commit comments

Comments
 (0)