Signal and SIGCHLD, what does it do?
c, fork, signals
Solution
Odd program.
What I think it is 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.
Problem
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?