process scheduling – SIGALRM not terminating a program after the specified time

I have written a C code, where the aim is to take N as an input and then create N processes and create some children of their own. Finally, each process sends each other SIGUSR1 signal after every 2 second. The idea is to close all the process after 10 seconds using SIGALRM but the program doesn’t terminate. If a take N as an input through command line, the program works but if taken through scanf, it somehow breaks. TIA


int main(void){

  int n;
  printf("enter N - ");
  scanf("%d", &n);

  int id1 = 1, id2 = 1;    //////// ids for tracking the process
  for(int i = 0; i<n; ++i){
    if(id1>0 && id2>0){     /////// only the grandparent can enter
      id1 = fork();
      int z = getpid()%13;
      for(int j = 0; j<z; ++j){
        if(id2>0 && id1==0)          //////// only the parent can enter
          id2 = fork();
      }
    }
  }

  alarm(10);          ///////// alarm for 10 seconds after which process stops sending SIGUSR1 and exits

  while(1){                       /////// SIGUSR1 signal
    sleep(2);
    for(int i = 1; i<13; ++i)
      kill(getpid()+i, SIGUSR1);
  }

  for(int i = 0; i<n*13; ++i)
    wait(NULL);

}

```