[英]scanf loop, and signal handler
剛剛學習了有關泛化的知識,還實現了另一個計時器,使其變得更加有趣。
#include <stdio.h>
#include <signal.h>
#include <sys/time.h>
volatile sig_atomic_t gotsignal;
void handler(){
gotsignal = 1;
}
int main(){
struct sigaction sig;
struct itimerval timer;
timer.it_value.tv_sec = 5;
timer.it_value.tv_usec = 0;
timer.it_interval = timer.it_value;
sig.sa_handler = handler;
sig.sa_flags = 0;
sigemptyset(&sig.sa_mask);
setitimer(ITIMER_REAL, &timer, 0);
sigaction(SIGALRM, &sig, NULL);
int value, y = 100, x=0;
while(!gotsignal && x < y){
printf("Insert a value: \n");
scanf("%d", &value);
x+=value;
printf("Current x value: %d\n", x);
}
}
我不明白的是,當它正在等待用戶輸入時,我寫了5,但沒有按Enter。 他還讀嗎? 他不應該清除嗎? 它給我的輸出:
Insert a value:
1
Current x value: 1
Insert a value:
2
Current x value: 3
Insert a value:
5Current x value: 5
我想要的是:
Insert a value:
1
Current x value: 1
Insert a value:
2
Current x value: 3
Insert a value:
5(Wthout pressing enter!)Current x value: 3 (He would forget about 5 no?)
一個(學究地)正確的信號處理程序可以完成的工作很少:特別是設置一個volatile sig_atomic_t
變量(這是某種整數類型),並可能調用siglongjmp
[我什至不確定siglongjmp
]。
所以先聲明
volatile sig_atomic_t gotsignal;
那么你的信號處理器就是
void handler (void)
{
gotsignal = 1;
}
你的循環是
while(!gotsignal && x < y){
printf("Insert a value: \n");
scanf("%d", &value);
x+=value;
}
不要忘記異步信號隨時發生 (任何機器指令!!!),包括在malloc
或printf
內部。 切勿從處理程序內部調用這些函數。
與不良信號處理相關的錯誤很難調試 :它們是不可復制的 !
考慮使用sigaction 。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.