i am struggling a bit to understand the output to the following c program
#include <stdio.h>
#include <pthread.h>
#include <unistd.h>
#include <sys/wait.h>
int main(void) {
int i = 1;
pid_t childId = fork();
pid_t pid = getpid();
if (childId == -1) {
perror("fork() failed");
} else if (childId == 0) {
printf("child PID: %d\n", pid);
int *j = NULL;
j = &i;
(*j)++;
printf("value i in child: %d\t@adresse: %p\n",i ,&i);
} else {
pid_t pid = getpid();
printf("parent PID: %d\nwait for child\n", pid);
waitpid(childId, NULL, 0);
printf("value i in parent: %d\t@adresse: %p\n",i ,&i);
}
return 0;
}
output:
parent PID: 10656
wait for child
child PID: 10657
value i in child: 2 @address: 0x7fff93b720c0
value i in parent: 1 @address: 0x7fff93b720c0
The child thread increments 'i' which is stored at the given address. After waiting for the child the parent thread continues execution and prints the 'i' at the same address but with the initial value. Shouldnt this be 2 as well?