【发布时间】:2012-12-01 17:31:03
【问题描述】:
自昨晚以来,我一直被这个问题困扰着,我希望第二双新的眼睛会有所帮助。
问题是,如果在userIn 函数中输入了无效的输入(任何不是 1-99 之间的数字),main 中 while 循环结束时的测试 printf 将打印“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;
}
【问题讨论】:
标签: c while-loop freeze