Here's a simple Python program:
s = input('Name: ')
I ran the program, typed a few letters, and then pressed Ctrld:
$ python3 myscript.py
Name: myverylongna
Nothing happens, so I press Ctrld again. Nothing happens. Then I press Ctrld for the third time. Python finally exits. I observe the same behavior using Python 2.7.
I don't understand why I had to press Ctrld three times to quit Python. For comparison, I wrote a C program to ask for user input (warning: the code has many mistakes):
#include <stdlib.h>
#include <stdio.h>
/* Asks the user for string input.
* Returns a pointer to the string entered by the user.
* The pointer must be freed.
*/
char* input()
{
char *s = malloc(sizeof(char));
if (s == NULL) {
fprintf(stderr, "Error: malloc\n");
exit(1);
}
char ch;
size_t s_len = 0;
while((ch = (char) getchar()) != '\n' && ch != EOF) {
s[s_len] = ch;
s_len++;
s = realloc(s, (s_len + 1) * sizeof(char));
if (s == NULL) {
fprintf(stderr, "Error: realloc\n");
exit(1);
}
}
s[s_len] = '\0';
return s;
}
int main()
{
printf("Name: ");
char *s = input();
free(s);
return 0;
}
The C program only requires two presses of Ctrld for a similar input. Why?
Why does python need three presses of Ctrld to quit the program when the user is in the middle of entering characters at an input prompt?
(I am running Python 3.6.8 on Ubuntu 18.04)