Home > Enterprise >  Sleep system call force a context switch? - C
Sleep system call force a context switch? - C

Time:09-27

I am trying to improve my understanding about scheduling and handling signals and I'm trying to solve a problem which its result are not very clear to me. Consider the following code :

void sUsr()
{
 printf("A1\n")
 sleep(1)
 printf("A2"\n)
}

int main(int argc, const char* argv[])
{
 sturct sigaction sa;
 sigfillset(&sa.sa_mask);
 sa.sa_handler = &sUser
 sigaction(SIGINT, &sa, NULL)
 sigaction(SIGSTP, &sa, NULL)
 kill(getpid(). SIGINT);
 kill(getpid(), SIGSTP);
}

I am trying to figure all the possible printing options. My "guidelines" :

  1. sigfillset blocks all signals which arrive while handling a signal.
  2. signal handling comes to place when switching from kernel to user.
  3. kill is a sys call.

I don't understand why the system can't print only "A1\nA2\n" When the first signal gets handle (first transition from kernel to user because of first kill call) the OS calls sUsr and prints "A1". Then, the sleep sys call gives the control back to main process which call second kill call but it can't be done because of the blocking mask. Time period of sleep passed and we go back to handle the system call and now the handler prints "A2".

The handler runs in user space thus the pending signal won't be handle (no switching from kernel to user) and the process stop existing. Unfortunately I am mistaken and I would like to understand where my suggested solution fails.

EDIT : the solution given to me is that the only printing option for this program is "A1\nA2\nA1\n\A2\n"

CodePudding user response:

The SIGSTP signal is blocked whilst the SIGINT signal handler is running but it is not lost. It becomes pending. So as soon as the SIGINT handler completes the next signal handler will be called to handle the SIGSTP.

OT: Note that printf is technically not an async safe function and should not be called in signal handlers.

  • Related