usleep just isn't waiting any time, the errno variable accuses an invalid argument is being passed on to the function, even if i use the useconds_t type I just get the same error over and over.
I have no idea what's going on here, here's the file I made for some testing.
#include <stdio.h>
#include <unistd.h>
#include <errno.h>
int main() {
unsigned int delay=500000;
int err=errno;
printf("%d\n", err);
usleep(delay);
err = errno;
printf("%d\n", err);
return 0;
}
strace output:
execve("./a.out", ["./a.out"], 0x7fffec458c30 /* 22 vars */) = 0
arch_prctl(0x3001 /* ARCH_??? */, 0x7ffff9f5d4f0) = -1 EINVAL (Invalid argument)
brk(NULL) = 0x1757000
brk(0x17581c0) = 0x17581c0
arch_prctl(ARCH_SET_FS, 0x1757880) = 0
uname({sysname="Linux", nodename="DESKTOP-PRJN4N7", ...}) = 0
readlink("/proc/self/exe", "/mnt/c/Users/User/dmsh/gm/a.out", 4096) = 31
brk(0x17791c0) = 0x17791c0
brk(0x177a000) = 0x177a000
mprotect(0x4bd000, 12288, PROT_READ) = 0
fstat(1, {st_mode=S_IFCHR|0660, st_rdev=makedev(0x4, 0x1), ...}) = 0
ioctl(1, TCGETS, {B38400 opost isig icanon echo ...}) = 0
write(1, "0\n", 20
) = 2
clock_nanosleep(CLOCK_REALTIME, 0, {tv_sec=0, tv_nsec=500000000}, NULL) = -1 EINVAL (Invalid argument)
write(1, "22\n", 322
) = 3
exit_group(0) = ?
+++ exited with 0 +++
The path in that line suggests you're using WSL to run your program in Windows, not a straight up Linux or Unix system.
And that one tells us you're using a glibc version in WSL that implements
usleep()in terms ofclock_nanosleep()(My Ubuntu 16.04 WSL installation usesnanosleep(), fwiw. Apparently the glibc people changed theusleep()implementation at some point.)The WSL linux emulation layer doesn't support
clock_nanosleep()with aCLOCK_REALTIMEtimer. To verify, this demo program:should print out
when you compile and run it.
The fix is to just not use
usleep()(Which is deprecated anyways and no longer in POSIX). Trynanosleep()or the aboveclock_nanosleep()with a monotonic timer.