My program gets stuck in the simple call usleep(1.);
. How can that be? What should I look out for?
Edit:
To make things even more confusing, it only gets stuck if I call rand() before:
rand();
usleep(1.);
Both calls individually are just fine.
Edit 2:
Here is a minimal example that works:
#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;
}
This one also works:
#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;
}
However, this one does not:
#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;
}
I compile these with gcc version 4.4.6 using the command gcc -std=c99 main.c
. Is the option -std=c99
the problem? But I still don't understand what's going on here.
POSIX. 1-2001 declares this function obsolete; use nanosleep(2) instead. POSIX. 1-2008 removes the specification of usleep().
On 8.1/2012R2/10/2016/2019/11/2022, waitable timers with 100-nanosecond resolution are available, so usleep() has microsecond accuracy.
You're calling usleep()
with a double
value, while it's specified to take an unsigned integer of type useconds_t
with limited range. See the manual page.
Perhaps the conversion fails, on your platform. Try removing the period, and just call it with 1
.
Don't introduce casts, it's best to not mention the useconds_t
type.
Also, note that this function is obsolete, new POSIX code should use nanosleep()
instead.
UPDATE By the way, the manual page linked above also seems to imply that you should #define
the proper symbols as listed before #include <unistd.h>
, to get this function. You should try that, if you're not getting the prototype the argument will not be automatically converted from double
. The (ignored) return value from rand()
might also be in some register or on the stack, causing things to further change in that case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With