自昨晚以来,我一直断断续续地遇到这个问题,我希望第二双新鲜的眼睛会有所帮助。
问题是,如果在函数中输入了无效输入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;
}