自昨晚以来,我一直断断续续地被这个问题困扰,我希望第二双新的眼睛能有所帮助。
问题是,如果在 userIn
函数中输入了无效输入(任何不是 1-99 之间的数字),则在 的 while 循环结束时测试 printf main
打印“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;
}
最佳答案
与您的直觉相反,程序在printf("HELLO");
行之后 某处卡住。由于您在该 printf 中没有换行符,因此 HELLO
被缓冲并且不会立即刷新到终端。
是否有进程从您的管道的另一端读取数据?
关于c - 输入有效输入后,While 循环会挂起程序吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13866403/