While loop hangs program after valid input is entered?

I have been stuck with this problem on and off since last night and I'm hoping a second fresh pair of eyes will help.

The problem, if an invalid input is entered in the userIn function (anything that isn't a number between 1-99) the test printf at the end of the while loop in main prints "ERR = 1", the while loops and userIn is called again. So far so good, but when a valid input is entered the test printf at the end of the while loop prints "ERR = 0" and then the program hangs. The test printf saying "HELLO" never gets printed.

Any suggestions as to why are most welcome.

The code:

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

void userIn (int *x)
    {
    char b;
    printf("Please enter a new value for Vm: ");
    scanf(" %i",x);
    while (((b=getchar())!='n')&&(b!=EOF));
    return; 
    }
int main (void)
    {
    int  fd, x, err;
    char *npipe = "/tmp/fms",
         input[3];
    struct stat info;
    printf("n");

    //get user input
    err = 1;
    while (err)
        {
        userIn(&x);
        if (x > 0 && x < 100) err = 0;
        //else printf("33[1A33[K");

        printf("ERR = %in",err);//TEST PRINTF
        }
    printf("HELLO");//TEST PRINTF

    //if pipe exists
    if ( (!lstat(npipe,&info)) && (S_ISFIFO(info.st_mode)) )
        {
        sprintf(input,"%i",x);
        //write user input to named pipe created by 'parent.c'
        fd = open(npipe, O_WRONLY);
        write(fd, input, sizeof(input));
        close(fd);
        }
    else printf("33[0;31mNamed pipe doesn't exist, %i not passed.nn33[0m",x);
    return 0;
    }

If I run your code on my system the output looks like this:

Please enter a new value for Vm: 101
ERR = 1
Please enter a new value for Vm: 1
ERR = 0
HELLONamed pipe doesn't exist, 1 not passed.

That is, the loop exits exactly when you think it should. Of course, the code then exits immediately because /tmp/fms does not exist on my system.

However, if I create /tmp/fms , then I see:

Please enter a new value for Vm: 1
ERR = 0

...and no additional output. This is because the output from the printf statement is buffered, and the write to the named pipe is blocking, so the output never gets flushed. Adding a n to your printf will probably display it as you expect.


Contrary to your intuition, the program freezes somewhere after the printf("HELLO"); line. Since you don't have a newline in that printf, HELLO gets buffered up and is not flushed to the terminal immediately.

Is there a process reading from the other end of that pipe of yours?

链接地址: http://www.djcxy.com/p/72190.html

上一篇: scanf和错误的输入会使输出变得更加奇怪

下一篇: while循环在输入有效输入后挂起程序?