0

自昨晚以来,我一直断断续续地遇到这个问题,我希望第二双新鲜的眼睛会有所帮助。

问题是,如果在函数中输入了无效输入userIn(不是 1-99 之间的数字),则在 while 循环结束时的测试 printfmain打印“ERR = 1”,while 循环并userIn再次被调用. 到目前为止一切顺利,但是当输入有效输入时,while 循环结束时的测试 printf 会打印“ERR = 0”,然后程序挂起。测试 printf 说“HELLO”永远不会被打印出来。

任何关于为什么的建议都是最受欢迎的。

编码:

#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("\033[1A\033[K");

        printf("ERR = %i\n",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("\033[0;31mNamed pipe doesn't exist, %i not passed.\n\n\033[0m",x);
    return 0;
    }
4

2 回答 2

2

与您的直觉相反,程序在该行之后printf("HELLO");的某处冻结。由于您在该 printf 中没有换行符,因此HELLO会被缓冲并且不会立即刷新到终端。

是否有从您的管道另一端读取的进程?

于 2012-12-13T18:53:30.817 回答
1

如果我在我的系统上运行您的代码,输出如下所示:

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.

也就是说,循环恰好在您认为应该退出的时候退出。当然,代码然后立即退出,因为/tmp/fms我的系统上不存在。

但是,如果我创建 /tmp/fms,那么我会看到:

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

...并且没有额外的输出。这是因为printf语句的输出是缓冲的,而对命名管道的写入是阻塞的,所以输出永远不会被刷新。将 a 添加\n到您的 printf 可能会按您的预期显示它。

于 2012-12-13T18:55:09.320 回答