2

I am new to C++. Is it possible to declare a variable for shared use between parent and child processes in fork()?

#include <iostream>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/wait.h>

using namespace std;

int var;

int main(int argc, char * argv[])
{       
    pid_t child_pid;
    int status;

    var = 3;

    if ((child_pid = fork()) < 0) {
        perror("Error (fork failure)");
    }   

    if (child_pid == 0) {
      var = 10;
      cout << "CHILD ASSIGNED var=" << var << endl;
    }    
    else {        
        wait(NULL);
        cout << "PARENT var=" << var << endl;
    }                        
}

The current result I get is:

CHILD ASSIGNED var=10
PARENT var=3

What I want is

PARENT var=10
sda
  • 143
  • 1
  • 10
  • What OS do you need to support (http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2006/n2044.html suggests that Windows and POSIX-y OS's (e.g. Linux and OSX) can use the same or similar mechanisms nowadays; this wasn't the case the last time I used shared memory – Foon Jul 22 '15 at 12:49
  • Does this answer your question? [Using shared memory with fork()](https://stackoverflow.com/questions/6449343/using-shared-memory-with-fork) – user202729 Jan 20 '21 at 10:37

1 Answers1

3

Not like that it isn't. After a fork the processes run in different memory spaces, and there's no relationship between the var in the parent and the var in the child.

You need to find some other way of communicating the information. You could make both processes attach to a shared memory object and for the child to update that, and for the parent to read it, although you also have to be careful about race hazards.

Alternatively, you could consider using threads, in which case both processes use the same memory, though again synchronisation is an issue.

Tom Tanner
  • 9,244
  • 3
  • 33
  • 61