0

I tried to allocate some memory in parent and tried to pass pointer to that memory to child and child to change value of it by double-ptr-de-referencing but it failed. it access the value and shows value correctly but when it's changed parent cant still get change in variable's value.


#include <sys/stat.h>
#include <fcntl.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <unistd.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>

int main() {

    int pipeVariable[2] = {0};

    pipe(pipeVariable);

    int x = fork();

    if(x == -1){
        perror("Error spawning child process");
        exit(1);
    }
    else if(x == 0){
        
        int *value = NULL;

        read(pipeVariable[0], value, sizeof(int));

        printf("Child \nMemory block : %p\nValue : %d\n", value, *value);

        printf("Child Changed the value\n");

        *value = 10;

        printf("Child \nMemory block : %p\nValue : %d\n", value, *value);

        close(pipeVariable[1]);

        close(pipeVariable[0]);

        exit(0);

    }
    else{

        int *testVariable = malloc(sizeof(int));

        *testVariable = 1000;

        printf("Parent \nMemory block : %p\nValue : %d\n", testVariable, *testVariable);

        write(pipeVariable[1], testVariable, sizeof(int));     

        wait(NULL);   

        printf("Parent \nMemory block : %p\nValue : %d\n", testVariable, *testVariable);

        free(testVariable);

        close(pipeVariable[1]);

        close(pipeVariable[0]);
    }

    return 0;
}

Pls Find attached output Image

jugal Shah
  • 21
  • 3
  • 7
    That's because the two processes have separate address spaces. – 500 - Internal Server Error Oct 13 '21 at 16:17
  • You've to create a shared memory in order to share data between two processes. `shm_open` and `mmap` functions is what you're looking for – Harry Oct 13 '21 at 16:47
  • The child gets a copy of the parent's memory contents at the time of the `fork()`, but any changes to memory after the fork are local to the process. – Ian Abbott Oct 13 '21 at 16:50
  • The child is dereferencing a null pointer (`value`). That is bad. The output does not seem to agree with that though. Is the posted code missing a `malloc` call or something? – Ian Abbott Oct 13 '21 at 16:51

0 Answers0