1

I put a process to sleep. When a process is put to sleep, it is marked as being in a special state and removed from the scheduler's run queue, and I want to wake it up by sending a signal via the command line, how can I do that. Let's say I have this C code which uses sleep for 100 seconds.

What signal do I need to send in order to wake it up and make the return value to be the seconds that remain from the sleep?

#include <unistd.h>
#include <stdio.h>

int main(void)
{
    printf("Current Proc ID is: %d. Wake me Up!\n", getpid());

    int time_remain = sleep(100);
    printf("Time Remain of sleep: %d\n", time_remain);
    return 0;
}
  • Does this answer your question? https://stackoverflow.com/questions/61494611/c-c-how-to-exit-sleep-when-an-interrupt-arrives – Amit Singh Jan 04 '21 at 18:43
  • Read both [time(7)](https://man7.org/linux/man-pages/man7/time.7.html) and [signal(7)](https://man7.org/linux/man-pages/man7/signal.7.html). Your approach is not the best one. Perhaps use [ppoll(2)](https://man7.org/linux/man-pages/man2/ppoll.2.html) – Basile Starynkevitch Jan 04 '21 at 18:43
  • @Barmar Yes for me also but some how it doesn't print the remain time of `sleep`. – zer0-padding Jan 04 '21 at 18:45
  • I was wrong, the default handling of `SIGALRM` is to terminate the process. – Barmar Jan 04 '21 at 18:45
  • @BasileStarynkevitch I already did, *signal* didn't give good answer. – zer0-padding Jan 04 '21 at 18:45
  • 1
    You need to set a signal to disposition `SIG_IGN`, then send that signal. – Barmar Jan 04 '21 at 18:46
  • 1
    Looks like `SIGCONT` may do it (`kill -CONT PID`) — https://unix.stackexchange.com/questions/252507/how-can-i-wake-a-process-from-sleep-status-via-signal-or-proc#answer-252621 – Alex Jan 04 '21 at 18:46
  • @xandercoded It doesn't do anything for me. The program is just keep with the sleeping. – zer0-padding Jan 04 '21 at 18:48
  • 1
    I also tried `SIGURG` and `SIGCHLD`, since their default disposition is `SIG_IGN`, but they didn't work either. So you may need to establish an actual handler for a signal. – Barmar Jan 04 '21 at 18:50

1 Answers1

1

Assign a signal handler to a signal, then send that signal.

#include <unistd.h> // sleep
#include <stdio.h>
#include <signal.h>

void do_nothing(int ignore) {
}

int main(void)
{
    signal(SIGUSR1, do_nothing);
    printf("Remaining = %d\n", sleep(100)); // i.e the return value after 5 seconds will be 95
    return 0;
}
imac:barmar $ ./testsleep &
[1] 2179
imac:barmar $ kill -USR1 %1
Remaining = 95
[1]+  Done                    ./testsleep
Barmar
  • 741,623
  • 53
  • 500
  • 612