can anyone explain this output (operating system)?
while i'm studying the operating system course i didnt understand why the o开发者_StackOverflow中文版utput of the code below like this
the code:
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
int main (int argc, const char * argv[]) {
int value = 5;
pid_t pid = fork();
printf("pid = %d \n",pid);
if (pid == 0){
value+=15;
printf("Value ch :%d \n",value);
}
else {
if (pid > 0) {
wait(NULL);
printf("Value pr :%d \n",value);
exit(1);
}
}
return 0;
}
OUTPUT:
run
[Switching to process 24752]
Running…
pid = 24756
pid = 0
Value ch :20
Value pr :5
if value in child became 20 why after returning from child value = to 5
Because fork()
creates a new process, with its own address space. This address space is filled with a copy of the contents of the original address space. Therefore, changes made in one process don't affect the other.
In other words, it's because processes don't share memory (unless you explicitly force them to with mmap()
and so on).
Because the parent process memory is copied to the child process and further changes in the child process memory don't affect the parent's. fork pitfalls are interesting.
精彩评论