I use fork() to create 2 processes and want to be able to access the same variable (not a copy of the parents variable but the varialbe itself) from both the child and the parent. Is there a way to do so? It is an underlying property of the program that there will be no deadlocks so that is not an issue.
Naturally the program is due tomorrow at 5pm so I am very much looking forward to any advice you may have for me.
I tried reading/writing the variable to a file from both the child and the parent but apperantly TrueUnix 64 creates two separate files if two concurrently running processes try to open a file by the same name
Dumb question - did you close the file after using it each time? I haven’t done much Unix, but I’d be surprised if it didn’t let you open a file another still-active process had closed.
As you have discovered, fork() creates a completely separate memory space for the child process (as if it copied all information from the parent process to the child process) and changes in one do not reflect in the other.
I can see two means of solving your problem, the first (and the one I’d prefer) would be to use two threads instead of processes, threads can execute simultaneously but they share a memory space (modifications are visible in both processes, subject to memory visibility rules, and you’ll need to use thread synchronization to ensure safe access).
If you don’t consider threads an acceptable solution, then you’ll need to use some form of interprocess communications (IPC). You may want to look at shared memory (mmap(), I believe on unices), pipes (using pipe(), of course), sockets, or RPC. Of these solutions you’ll probably be happiest using shared memory, though I believe you’ll still need to use memory barriers to ensure correct reads/writes and synchronization to prevent concurrent writes. A shared memory region will let you share data of simple structure (it’s more complicated (though possible) to use pointers in a shared memory region (a piece of data may have a different address in each process sharing the region)) and from your description this should suffice.
Yup, shared memory would be the easiest. Theres a lot of esoteric commands to get it working but you dont really need to figure out what they do. Just use the default settings for everything.