1

Consider the following Pseudo-C code:

static int G = 0;
void alrm_handler(int signo) {
    G = 1;
}

void son() {
    struct sched_param param;
     param.sched_priority = 50;
    sched_setscheduler(getpid(),SCHED_FIFO, &param);
    kill(getppid(), SIG_ALRM);
    sched_yield();
    printf("A\n");
    while(1);
    exit(0);
}

int main() {
    signal(SIG_ALRM, alrm_handler);
    int son_pid = fork();
    if(son_pid==0)
        son();
    waitpid(son_pid);
    printf("B\n");
    return 0;
}

It's from an exam in OS. The question is as follows:

In multi cores CPU what would be printed?

The answers is that we can't know because it could be A and then B or B and then A. I don't understand why. If parent is waiting for the son with waitpid and the son sends signal SIG_ALRM which invokes the alrm_handler function for the parent, the parent will finish executing the function and then return to waiting the son until he will finish running, no? So it should be A and then B.

vesii
  • 2,760
  • 4
  • 25
  • 71
  • The "son" is running an infinite loop. So it'll be A followed by nothing as "son" process runs forever. – P.P Jul 26 '20 at 09:53
  • That what I think but the answer is that we can't know. My only guess is that `waitpid` does not wait to his son to finish – vesii Jul 26 '20 at 11:17
  • Why wouldn't waitpid wait? Also note `waitpid` (rather than `wait`) has an option to *not* wait (your pseudo code doesn't help things here). – P.P Jul 26 '20 at 11:21
  • Yes I agree. I just trying to figure out what the author of the question meant. As I understand `waitpid` will wait if it gets some value. – vesii Jul 26 '20 at 11:24

1 Answers1

0

According to POSIX it is undefined whether system calls are restarted after a signal handler set by signal is called.

  • System V and the Linux signal system call do not restart system calls.
  • BSD and by default GLibc, do restart system calls.

If System V signal is used waitpid can return as soon the signal has been sent, allowing the letters to be printed in any order. If standard output is a pipe or regular file only B will be output as the child is in a infinite loop

With BSD signal only A will be printed as waitpid does not return due to the infinite loop in the child. If standard output is a pipe or regular file only nothing will be output.

Timothy Baldwin
  • 3,551
  • 1
  • 14
  • 23