0

I am trying to understand how signal handler work. I saw an example on geeksforgeek:

int val = 10;
void handler(int sig){
    val += 5;
}

int main(){
    pid_t pid;
    signal(SIGCHLD, handler);
    if((pid = fork()) == 0){
        val -= 3;
        exit(0);
    }
    waitpid(pid, NULL, 0);
    printf("val = %d\n", val);
    exit(0);
}

I am confused about why the output value is 15. Initially, I guessed it is because the child process has variable val in different address. However, when I tried to print out the address of val in both child process and its parent process, they both display the same memory address.

Rachid K.
  • 4,490
  • 3
  • 11
  • 30
  • 1
    Read a text book about Unix/Linux programming. Without fundamentals you won't be able to ask your way through the subject. – Maxim Egorushkin Nov 16 '20 at 11:59
  • 1
    The address is the same because it is a copy of the process – stark Nov 16 '20 at 12:11
  • Yes. But if they have the same address, before child process ends, 3 will be subtracted from val, which gives 7, and then when the child process exits, the signal handler is invoked, then additional 5 will be added to val, thus, it should be 12 when it is printed out. – Joseph Cheng Nov 16 '20 at 12:29
  • The same *virtual* address. Google copy-on-write. A copy gets a different physical address when needed. – Eugene Ryabtsev Nov 16 '20 at 12:55

1 Answers1

2

The address that you print is a virtual address, it's the address of the global variable in the process's memory space. The child process and the parent process have memory spaces that look the same but they're not actually the same memory space (meaning they don't occupy the same physical memory).

this is a very high level (and somewhat inaccurate) answer, I suggest that you read about virtual memory in order to understand this properly.

Asaf Bialystok
  • 126
  • 1
  • 10