lecardo
lecardo

Reputation: 1212

C I believe my child process dies too quick to run my signal?

Got a bit of a weird situation here that I thought I'd solved using a alarm signal. I have a parent that forks for a child. Now in this child process, I want it to recognise "SIGTSTP" signal which is catching control + z.

To prevent the child from dying straight away, I placed in a alarm(5) signal to keep it running a bit longer. The child also has the call for the Control + Z SIGNAL. The problem I'm facing is, when I get to the run time of that particular code after compiling it, I press control Z and I get the result from the handler as expected however I also get on terminal :

[9]+ Stopped ./a.out

I can't seem to press control Z again though as nothing seems to work...eventually the alarm expires and the code just finishes execution? If I placed my handler for control Z in the parent process it all runs fine.

fork2 = fork();

    if (fork2 < 0)
    {
      write(2, "CHILD B FORK ERROR. \n", 21);
    }
    else if (fork2 == 0)
    {
      signal(SIGALRM, handleSignal);
          if (signal(SIGTSTP, handleSignal) == SIG_ERR)
        {
          write(2, "Error catching signal Z \n", 26);
        }
      write(1, "I am child of B \n", 17);

      alarm(5);
    }
    else
    {
        // where parent code is
    }

Upvotes: 0

Views: 46

Answers (1)

SamC
SamC

Reputation: 71

I think you are misunderstanding how alarm(2) works. Alarm is not a blocking call and will not keep your child process alive longer. I suggest you use sleep(3) instead, sleep blocks for x seconds or until a signal arrives that is not ignored. I would write it something like this (untested, uncompiled code):

fork2 = fork();

if (fork2 < 0)
{
  fprintf(stderr, "CHILD B FORK ERROR.\n");
}
else if (fork2 == 0)
{
  if (signal(SIGTSTP, handleSignal) == SIG_ERR)
  {
    fprintf(stderr, "Error catching signal Z\n");
  }
  fprintf(stdout, "I am child of B \n");

  while(sleep(5) == 0);
}
else
{
    // where parent code is
}

I kept it pretty close to your sample, but I replaced the "write" calls by fprintf and added a while loop that checks if "sleep" returned a non-zero value (==> a signal interrupted the sleep). If I would write this code myself I would also not use signal(2), but sigaction(2).

Upvotes: 1

Related Questions