【发布时间】:2017-07-20 10:52:00
【问题描述】:
我知道 scanf 等待输入。 但是在我写的这个程序中,它正在打印 hello 在无限循环中。它不等我进入。
#include <signal.h>
#include <stdio.h>
#include <string.h>
#include <sys/time.h>
#include<unistd.h>
void timer_handler (int signum)
{
static int count = 0;
printf ("timer expired %d times\n", ++count);
}
int main ()
{
struct sigaction sa;
struct itimerval timer;
memset (&sa, 0, sizeof (sa));
sa.sa_handler = &timer_handler;
sigaction (SIGALRM, &sa, NULL);
timer.it_value.tv_sec = 0;
timer.it_value.tv_usec = 250000;
/* ... and every 250 msec after that. */
timer.it_interval.tv_sec = 1;
timer.it_interval.tv_usec = 250000;
/* Start a virtual timer. It counts down whenever this process is
executing. */
setitimer (ITIMER_REAL, &timer, NULL);
/* Do busy work.
*/
int i=0;
while(1){
scanf("%d",&i); //****Not waiting for input****
printf("hello");
}
}
输出:
计时器过期 1 次 你好计时器过期2次 你好计时器过期3次 你好计时器过期4次 你好计时器过期5次 你好计时器过期6次 你好计时器过期7次为什么?
?
【问题讨论】:
-
使用
scanf(" %d",&i);而不是scanf("%d",&i); -
@rsp 结果相同。
-
@rsp 所有
scanf()说明符,除了c,n,[首先使用前导空白。scanf(" %d",&i);中的建议空间用途不大。