Scanf 不等待输入
Scanf is not waiting for input
我知道 scanf 等待输入。
但是在我写的这个程序中它正在打印
你好 无限循环。它不等我进入。
#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");
}
}
输出:
timer expired 1 times
hello timer expired 2 times
hello timer expired 3 times
hello timer expired 4 times
hello timer expired 5 times
hello timer expired 6 times
hello timer expired 7 times
为什么?
?
POSIX 平台上的 scanf
函数在其实现的某处正在使用 read
系统调用。当计时器信号发生时,read
调用将被 中断 和 return 并出现错误 (EINTR
),这又会导致 scanf
return 也一样。您可以通过检查 scanf
returns 来检查这一点。在这种情况下,它应该 return EOF
而 errno
仍然设置为 EINTR
.
一个简单的解决方案是请求信号重新启动被中断的系统调用。这是通过在 sigaction
结构 sa_flags
成员中添加 SA_RESTART
标志来完成的:
sa.sa_flags = SA_RESTART;
更多信息可以在例如this POSIX sigaction
reference.
我知道 scanf 等待输入。 但是在我写的这个程序中它正在打印 你好 无限循环。它不等我进入。
#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");
}
}
输出:
timer expired 1 times hello timer expired 2 times hello timer expired 3 times hello timer expired 4 times hello timer expired 5 times hello timer expired 6 times hello timer expired 7 times
为什么?
?
POSIX 平台上的 scanf
函数在其实现的某处正在使用 read
系统调用。当计时器信号发生时,read
调用将被 中断 和 return 并出现错误 (EINTR
),这又会导致 scanf
return 也一样。您可以通过检查 scanf
returns 来检查这一点。在这种情况下,它应该 return EOF
而 errno
仍然设置为 EINTR
.
一个简单的解决方案是请求信号重新启动被中断的系统调用。这是通过在 sigaction
结构 sa_flags
成员中添加 SA_RESTART
标志来完成的:
sa.sa_flags = SA_RESTART;
更多信息可以在例如this POSIX sigaction
reference.