chhx001
chhx001

Reputation: 109

How can I use sleep() and timer in one program?

I want to use sleep() and timer in one program.

But when I use setitimer() in the program, sleep() loses its efficacy.

How can I make a timer while not disturbing sleep() to block the main thread?

Upvotes: 0

Views: 114

Answers (1)

Maxim Egorushkin
Maxim Egorushkin

Reputation: 136266

From man sleep:

sleep() may be implemented using SIGALRM; mixing calls to alarm(2) and sleep() is a bad idea.

Use nanosleep instead:

Compared to sleep(3) and usleep(3), nanosleep() has the following advantages: it provides a higher resolution for specifying the sleep interval; POSIX.1 explicitly specifies that it does not interact with signals; and it makes the task of resuming a sleep that has been interrupted by a signal handler easier.

Upvotes: 1

Related Questions