我的程序卡在了简单的调用 usleep(1.);
中。这个怎么可能?我应该注意什么?
编辑:
为了让事情变得更加困惑,只有在我之前调用 rand() 时它才会卡住:
rand();
usleep(1.);
两个单独调用都很好。
编辑 2:
这是一个有效的最小示例:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
printf("Calling rand() and then usleep(1) on pid %d \n",getpid());
rand();
usleep(1);
printf("Finished.\n");
return 0;
}
这个也可以:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
printf("Calling usleep(1.) on pid %d \n",getpid());
usleep(1.);
printf("Finished.\n");
return 0;
}
但是,这个不会:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
int main(int argc, char* argv[]) {
printf("Calling rand() and then usleep(1.) on pid %d \n",getpid());
rand();
usleep(1.);
printf("Finished.\n");
return 0;
}
我使用命令 gcc -std=c99 main.c
使用 gcc 4.4.6 版编译它们。是选项 -std=c99
的问题吗?但我还是不明白这是怎么回事。
最佳答案
您正在调用 usleep()
用double
值,而它被指定为采用 useconds_t
类型的无符号整数范围有限。参见 the manual page .
也许在您的平台上转换失败。尝试删除句点,然后用 1
调用它.
不要介绍cast,最好不要提useconds_t
类型。
另请注意,此函数已过时,新的 POSIX 代码应使用 <a href="http://linux.die.net/man/2/nanosleep" rel="noreferrer noopener nofollow">nanosleep()</a>
相反。
更新 顺便说一句,上面链接的手册页似乎也暗示你应该 #define
之前列出的正确符号 #include <unistd.h>
, 得到这个函数。你应该试试看,如果你没有得到原型(prototype),参数将不会从 double
自动转换。 .来自 rand()
的(忽略的)返回值也可能在某些寄存器或堆栈中,导致事情在这种情况下进一步改变。
关于c - 陷休眠眠状态(1.),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14340485/