1

I try to run 2 parallel processes i have a global variable x = 0 process A: increase global variable x by 1 process B: print x

I followed this example How to run two child processes simultaneously in C? but i always end up printing zeros

    #include <stdlib.h>
#include <stdio.h>
#include <unistd.h>

int main()
{
    int x = 0;
    int i;
    pid_t child1, child2;

    if (!(child1 = fork()))
    {
        // first childi
        while(1)
        {
            x = x + 1;
        }
    }
    else if (!(child2 = fork()))
    {
        // second child
        while(1)
        {
            printf("%d", x);
        }
    }
    else
    {
        // parent
        wait(&child1);
        wait(&child2);
    }

    return 0;
}
  • 5
    It is important to know that a copy of the memory is used by each forked process (well ... not exactly, take a look to [How does copy-on-write work in fork()?](https://stackoverflow.com/questions/27161412/how-does-copy-on-write-work-in-fork)), both for the heap and the stack. To share memory between processes you must use some mechanism that allows it, i.e. `mmap`. Or you may be more interested in creating two threads and using a mutex or an atomic type: `atomic_int x;` – David Ranieri Dec 19 '22 at 10:35
  • 1
    Unless you explecitly tell the OS to share memory between processes, it is not. By the way, note that `while(1) { x = x + 1; }` could be optimized by the compiler so `x` is not updated. Fun fact: Clang does optimize this in `-O3` for example for `x` is left unmodified. – Jérôme Richard Dec 19 '22 at 16:15

0 Answers0