3

I am using a timer in my C++ code through setitimer function from sys/time.h. This maps the SIGALRM signal to my timer handler method. After this I am not able to use sleep function. I am assuming it is because sleep uses SIGALRM signal as well. Can you suggest any workaround for this problem?

Thanks for replying.

1
  • +1 I'm sure I'll run into this problem myself sooner or later.
    – FireAphis
    Sep 5, 2010 at 4:54

3 Answers 3

8

From the alarm(2) man page:

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

Some implementations don't use SIGALRM, find a machine like that and you're set. Otherwise, you can try nanosleep(); it's implemented safely. From the nanosleep(2) man page:

Compared to sleep(3) and usleep(3), nanosleep() has the advantage of not affecting any signals, it is standardized by POSIX, it provides higher timing resolution, and it allows to continue a sleep that has been interrupted by a signal more easily.

1
  • When I use nanosleep() along with setitimer(), the timer handler gets executed at different intervals on Asus Tinkeboard. Am I missing something? Jul 31, 2018 at 11:02
3

You can try using select() just as a timer. I don't know if it uses SIGALRM or not but it should be simple to test. Something like:

   timeval t = {1, 0};

   select(0, NULL, NULL, NULL, &t);
1
  • ACE uses select to implement the timer, so I guess your suggestion should work.
    – FireAphis
    Sep 5, 2010 at 4:56
0

I'd use a library that gives an abstraction to these OS services. I use ACE library for timers and sleeps (ACE_OS::sleep, ACE_Reactor::schedule_timeout) and they work together without any problems. As far as I know ACE uses select for its timers. I guess boost::thread::sleep and boost::asio::deadline_timer will accomplish the task successfully as well.

2
  • Unfortunately it is required that I not use any third party libraries. I cannot use Boost or ACE :( .
    – SkypeMeSM
    Sep 5, 2010 at 4:45
  • Well, then I guess Carl just gave the definitive answer :) (running to his post to vote it up).
    – FireAphis
    Sep 5, 2010 at 4:49

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.