Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Signal and SIGCHLD, what does it do?

Tags:

c

fork

signals

i am asked to find all the possible outputs in this question:

#define N 4
int val = 9;
void handler(sig) {
   val += 3;
   return;
}
int main() {
  pid_t pid;
  int i;
  signal(SIGCHLD,handler);
  for (i=0;i<N;i++) {
    if ((pid =fork()) == 0) {
        val -= 3;
        exit(0);
    }
  }
  for (i=0;i<N;i++) {
    waitpid(-1,NULL,0);
  }
  printf("val = %d\n",val);
}

I do not know what the line signal(SIGCHLD, handler) does. I only found the following:

SIGABRT - abnormal termination.
SIGFPE - floating point exception.
SIGILL - invalid instruction.
SIGINT - interactive attention request sent to the program.
SIGSEGV - invalid memory access.
SIGTERM - termination request sent to the program.

what does SIGCHLD do? Can you also explain the for loop in this question as well?

and what necessary libraries do I need to compile and run this code?

like image 633
PhoonOne Avatar asked Feb 19 '23 05:02

PhoonOne


2 Answers

When you fork a child process from a parent process, the SIGCHLD is set but the handler function is NOT executed. After the child exits, it trips the SIGCHLD and thus causes the code in the handler function to execute...

like image 169
Ram Avatar answered Feb 20 '23 21:02

Ram


Odd program.

What I think it i trying to shows you is what SIGCHLD causes and how a variable in a child process being changed by the child, has no effect in the parent.

When you fork() you create a child process. Sound familiar? The parent process ( the one that called fork() ) receives the signal. The handler is executed. When you run the program you should see out of 21.

This is because val is incremented by three every time the signal handler is executed 9 + ( 3*4)=21. The code creates four children.

The child process

val -= 3; exit(0);

decrements val. But because this happens in another process, not the original child, it does not touch the "original" val variable because it has its own local copy.

like image 38
jim mcnamara Avatar answered Feb 20 '23 20:02

jim mcnamara