Question

while i'm studying the operating system course i didnt understand why the output 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

Was it helpful?

Solution

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).

OTHER TIPS

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.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top