Search code examples
clinuxsignalssleep

msleep(msec) vs msleep_interruptible(msec)


I don't understand usage for these: msleep and msleep_interruptible ... I know one interruptible and other is non-interruptible but couldn't find certain usage where I can actually see. I tried calling thread with function to msleep and print say "Hello!" and msleep(msleep_interruptible) after that, but couldn't see any difference. Can anyone help me with that, may be with example?


Solution

  • The difference is in what happens when a signal (e.g. SIGINT) is raised and you set a signal handler for that signal.

    • msleep goes back to sleep
    • msleep_interruptible returns to the caller (with a non-zero value representing the sleep time remaining).

    An example of an interruptible sleep:

    $ perl -Mthreads -E'
       my $stime=time;
       async { sleep(3); kill INT => $$; }->detach();
       $SIG{INT} = sub { warn "Got INT signal after ".(time-$stime)."\n"; };
       sleep(5);
       say time-$stime;
    '
    Got INT signal after 3
    3
    

    It slept for 3 seconds instead of 5 because it got interrupted by a handled signal. The other version would print the following:

    Got INT signal after 3
    5
    

    In other words, the signal handler gets called either way, but one version doesn't return even if a signal comes in.