问题描述
我正在尝试编写一个小程序,可以睡5秒钟。
但是,如果用户按下Ctrl-C,它会中断睡眠并打印
未支付金额。
例如:
unix> ./sleeper
睡5秒
未睡眠金额为2(用户在3秒后点击Ctrl-C)
unix>
下面的代码出了什么问题?
----------------------- --------
#include< stdio.h>
#include< stdlib.h>
#include< signal.h>
unsigned int unslept;
void handler(int sig)
{
printf(" unslept amount is%d",unslept);
退出(0);
}
int main()
{
信号(SIGINT,处理程序);
printf(睡觉持续5秒\ nn);
unslept = sleep(5);
返回0;
}
I am trying to write a little program that goes to sleep for 5 seconds.
However, if the user presses Ctrl-C, it interrupts the sleep and prints the
unslept amount.
For example:
unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3 seconds)
unix>
What''s wrong with the code below?
-------------------------------
#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
unsigned int unslept;
void handler (int sig)
{
printf("unslept amount is %d",unslept);
exit(0);
}
int main()
{
signal(SIGINT,handler);
printf("sleeping for 5 seconds\n");
unslept = sleep(5);
return 0;
}
推荐答案
< snip>
您正在寻找comp.unix.programmer。 sleep()是一个非标准函数。
另见。
S.
<snip>
You''re looking for comp.unix.programmer. sleep() is a nonstandard function.
Also see http://www.ungerhu.com/jxh/clc.welcome.txt.
S.
3秒钟后,您向程序发送了一个信号(SIGINT)和
按Ctrl + C键。你进入你的处理程序
并退出。
你还想要什么?
信号是异步的在C.
程序做某事可以随时被重定向到一个信号
处理程序。
这个是正常行为。
jacob
After 3 seconds you sent the program a signal (SIGINT) with
the Ctrl+C keys. You got into your handler procedure
and exited.
What else do you want?
Signals are asynchronous in C.
Programs doing something can at any moment be redirected to a signal
handler.
This is normal behavior.
jacob
我希望它打印出来的时间正确。我的代码总是在零时间内打印ZERO
。
unix> ./sleeper
睡5秒
未睡眠金额为0(此行打印用户
按Ctrl-C,未睡眠金额总是零)
unix>
我想让它打印剩下的睡眠时间。例如,如果用户
在三秒钟后按Ctrl-C,那么它应该打印2以获得未睡眠时间:
unix> ./sleeper
睡5秒
未睡眠金额为2(用户在3 / b
秒后按Ctrl-C)
unix>
----
谢谢。
Syed
I want it to print the unslept time correctly. My code always prints ZERO
for unslept time.
unix> ./sleeper
sleeping for 5 seconds
unslept amount is 0 (This line prints when user
hits Ctrl-C, unslept amount is always zero)
unix>
I want it to print the acutal time left to sleep. For example if the user
hits Ctrl-C after three seconds, then it should print 2 for unslept time:
unix> ./sleeper
sleeping for 5 seconds
unslept amount is 2 (User hits Ctrl-C after 3
seconds)
unix>
----
Thanks.
Syed
这篇关于睡觉()行为不端的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!