How to avoid the interruption of sleep calls due to a signal in Linux?

柔情痞子 提交于 2019-12-05 04:04:42

From the nanosleep manpage:

nanosleep delays the execution of the program for at least the time specified in *req. The function can return earlier if a signal has been delivered to the process. In this case, it returns -1, sets errno to EINTR, and writes the remaining time into the structure pointed to by rem unless rem is NULL. The value of *rem can then be used to call nanosleep again and complete the specified pause.

You can mask almost all signals (except SIGKILL) using sigprocmask() or signal() calls. The first one will return you the previous mask, which you can recover after sleep(). Some examples are here. If that does not help, please, be more verbose of what signal interrupts your sleep. I think, you can additionally check this condition ("sleep interrupted by signal?") and fall into sleep again.

Newer Linux kernels support signalfd(2). That, together with sigprocmask(2), is a very nice way to combine handling of signal and IO events in a single epoll_wait(2) call.

If you don't want to be interrupted, why are you using the real time signal?

Somewhere, either in Rockind's "Advanced Unix Programming" or Steven's book, there was an example of how to fake this out. You make note of the current time_t before starting your sleep. After the sleep ends, you check to make sure the required amount of time has elapsed, and if it hasn't, you start a new sleep. Put the sleep in a loop that calculates the time to go and sleeps that amount, and exits when the required time has passed.

Well, a realtime signal is supposed to interrupt sleep. You could use a non-realtime signal instead. Another approach is to check if the expected time to sleep has elapsed, and if not, sleep for the remaining interval.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!