gpt4 book ai didi

c - sleep() C 没有返回正确的值

转载 作者:太空宇宙 更新时间:2023-11-04 07:59:16 25 4
gpt4 key购买 nike

我正在做一个学校项目(需要用 C 语言开发),我需要它在程序执行开始后每隔 X 秒和 Y 秒执行一些代码,它必须结束。

所以我写道:

alarm(Y);
s=X;
while(!end){
s = sleep(s); //because it generates some children that send signal to him and in that case i need to do other stuffs
if(s == 0){
//code to do each X seconds
}
}

变量 end 是一个初始化为 0 的全局变量,当收到 SIGALARM 时,该值变为 1。

如果我有 X>Y,则不应执行每 X 秒执行一次的代码,但如果 X=Y+1,则执行一次。

你能告诉我为什么会这样吗?

最佳答案

Per the manual :

DESCRIPTION

sleep() causes the calling thread to sleep either until the number of real-time seconds specified in seconds have elapsed or until a signal arrives which is not ignored.

RETURN VALUE

Zero if the requested time has elapsed, or the number of seconds left to sleep, if the call was interrupted by a signal handler.

您对 alarm() 的使用几乎肯定会中断您的 sleep() 调用。

即使 alarm() 没有干扰,sleep() 也可能总是被信号打断,而且你有妥善处理。

关于c - sleep() C 没有返回正确的值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47830765/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com