ctrl-d appends characters to output

Montgomery-Smith, Stephen stephen at missouri.edu
Sat Jan 17 21:02:29 UTC 2015


On 01/17/2015 02:16 PM, Montgomery-Smith, Stephen wrote:
> On 01/17/2015 11:59 AM, less xss wrote:
>> I've searched around quite a bit with no luck on this matter. I currently
>> have an issue where I send EOF (ctrl-d) to some simple K&R2 exercises and
>> the terminal returns the D character appended to my data when EOF is sent.
>> I wish to prevent any and all extra characters from being appended and I
>> would also like to understand why it's happening. The following code
>> is an example exercise from K&R2 that yield said problem.
>>
>> #include <stdio.h>
>>
>> int main() {
>>     double nc;
>>
>>     for (nc = 0; getchar() != EOF; ++nc) {
>>         ; /* syntactic null statement */
>>     }
>>
>>     printf("%.0f\n", nc);
>> }
>>
>> $ ./a.out
>> 0D
>> $
> 
> I did a bit of experimenting with this issue.  First, I cannot reproduce
> it on my Linux box.  Second, this simpler program does the same thing:
> 
> #include <stdio.h>
> 
> int main() {
> 
>     while (getchar() != EOF) {
>         ; /* syntactic null statement */
>     }
> 
>     printf("\n");
> }
> 
> In this case I get:
> 
> % ./a.out
> ^D
> %
> 
> However, if I remove that last printf statement, then no ^D is displayed.
> 
> Considering the inconsistent nature of when this ^D appears, I would
> prefer to call it a bug than a feature.  But it must have been put there
> by design.

OK, that last printf is NOT responsible for the ^D.  It is just that the
prompt wipes it out.  Try this code:

#include <stdio.h>
#include <unistd.h>

int main() {

    while (getchar() != EOF) {
        ; /* syntactic null statement */
    }
    sleep(10);
}

Then the ^D shows until the prompt appears 10 seconds later.


More information about the freebsd-hackers mailing list