Search code examples
csignalssleep

Difference between `sleep` and `pause` library functions in unistd.h


From man page of pause

pause() causes the calling process (or thread) to sleep until a signal is delivered that either terminates the process or causes the invocation of a signal-catching function.

From man page of sleep

sleep() makes the calling thread sleep until seconds seconds have elapsed or a signal arrives which is not ignored.

/* This will wait till the signal arrives and it should be handled */
pause();

/* is it same as the above one */
/* This will also sleep for infinite time untill the signal arrives and it should be handled */
while (1) {
    int ret = sleep(3);
    if (ret != 0)
        break;
}

Source code of sleep and pause, both has been implemented in different way.

What is the difference between their implementation? From application point of view when to use pause and when to use sleep.


Solution

  • Both could be trivially implemented on a POSIX system by:

    #include <poll.h>
    int pause(){ return poll(0, 0, -1); }
    int sleep(unsigned int s){ return poll(0, 0, s * 1000); }
    

    In fact, the 2nd is cheating, as sleep should return the time still left to sleep if interrupted, but who really cares about that \;-.

    But it's exactly that complication the reason why sleep(3) is implemented in a more round-about way in the glibc source. Otherwise, any blocking non-restartable system call will do, including but not limited to nanosleep(2), poll(2), select(2) or sigsuspend(2). What to use is more a matter of compatibility.