0

How can I share data between child and parent in Linux (not Windows)?

Source files:

1.h

extern int a;
extern int b;

2.h

#include "1.h"

void adder();

2.c

#include "2.h"

void adder()
{
    a++;
    b++;
}

1.c

#include "1.h"
#include "2.h"

int a = 0;
int b = 0;

int main()
{
    pid_t pid;

    pid = fork();
    while (1) {
        if (pid == 0) {
            adder();
        }
        printf("a: %d , b: %d\n", a, b);
    }

    return 0;
}

result

a: 0  b: 0 

How can I share the values of a and b? I want to get the result that a and b are increasing.

dgvid
  • 26,293
  • 5
  • 40
  • 57
  • 1
    There are many ways to handle [inter-process communications](http://en.wikipedia.org/wiki/Inter-process_communication), if you want to share memory then [*shared memory*](http://en.wikipedia.org/wiki/Shared_memory_%28interprocess_communication%29) seem to be a good thing to look at. – Some programmer dude May 01 '15 at 12:26
  • 2
    `fork()` creates a full copy of your virtual memory, commonly using copy-on-write. Global variables are private to the process. If they *weren't*, non-atomic non-readonly access without synchronisation would be undefined beeahviour. – EOF May 01 '15 at 12:31
  • 1
    This one line you show is all the output you get? – alk May 01 '15 at 12:31
  • `This question already has an answer here:` in WinAPI!!! Good joke. – myaut May 01 '15 at 14:04

0 Answers0