You're calling fork() inside an if. fork() returns:
0 in the child process,the child's PID (>0) in the parent,-1 on error.
So in your snippet:
if (fork() == 0) { x += 2; }
only the child process will execute x += 2. The parent does not enter the if-block. After fork both processes continue independently with separate address spaces (copy-on-write), so changing x in the child does not affect x in the parent.
Example program:
include include include <sys/wait.h>
int main(void) { int x = 0; pid_t pid = fork(); if (pid == -1) { perror("fork"); return 1; } if (pid == 0) { / child / x += 2; printf("child: x = %d\n", x); } else { / parent / printf("parent: x = %d\n", x); wait(NULL); / avoid zombie / } return 0; }
Typical output (order may vary): parent: x = 0 child: x = 2
Notes:
Use wait()/waitpid() in the parent to avoid leaving a zombie child.If you need a value shared between parent and child, use shared memory (mmap, shm_open, etc.) or IPC; ordinary variables are not shared.fork() in multithreaded programs has additional caveats: only the calling thread is duplicated in the child.
You're calling fork() inside an if. fork() returns:
0 in the child process,the child's PID (>0) in the parent,-1 on error.So in your snippet:
if (fork() == 0) {
x += 2;
}
only the child process will execute x += 2. The parent does not enter the if-block. After fork both processes continue independently with separate address spaces (copy-on-write), so changing x in the child does not affect x in the parent.
Example program:
include include include <sys/wait.h>int main(void) {
int x = 0;
pid_t pid = fork();
if (pid == -1) {
perror("fork");
return 1;
}
if (pid == 0) { / child /
x += 2;
printf("child: x = %d\n", x);
} else { / parent /
printf("parent: x = %d\n", x);
wait(NULL); / avoid zombie /
}
return 0;
}
Typical output (order may vary):
parent: x = 0
child: x = 2
Notes:
Use wait()/waitpid() in the parent to avoid leaving a zombie child.If you need a value shared between parent and child, use shared memory (mmap, shm_open, etc.) or IPC; ordinary variables are not shared.fork() in multithreaded programs has additional caveats: only the calling thread is duplicated in the child.