It's true that a global (i.e.; external) variable IS available across processes, if its content is loaded before the fork.
Since I am really only interested in 2 primary concepts: shared memory and process management, you can put
ANYTHING in the shared memory (as long as all processes use it), either the result array or the file or both (or
anything else you need), however, putting the file, D, into global memory, instead of shared memory, WILL
make your program run differently. By putting it into a global variable, you are forcing the system to make a full
copy of that memory at FORK time. This can have a major impact on the system's overall memory availability.
This is especially important if the file is large. That is inefficient programming and, on a multi-user system,
makes the programmer a "bad-guy".
Putting the data in shared memory means there is really only ONE version of the data, not "N".
If you don’t share the file at all as a memory resource, you need to be careful to open the file as a SHARED file
(which may or may not be a default on a given system) or the processes WILL be serialized on that rsource
(which defeats the whole idea of concurrent processes).
#include <sys/shm.h> /* for shared memory on Linux/Solaris (see man shmget) */
extern int errno; /* for reporting additional error information */
Shared Memory Functions:
To obtain buffer and variable memory for sharing:
Note: in the code below, uppercase names are constants, either defined by you (using #define) or by the #include
files noted above.
#define SIZE 10 /* size of the shared buffer */
#define VARSIZE 1 /* size of shared variable=1byte in this example*/
#define SHMPERM 0600 /* shared memory permissions. This is a set of OR’d values */
int segid; /* id for shared memory buffer */
/* in “pre-fork” parent code: */
segid = shmget (IPC_PRIVATE, SIZE, IPC_CREAT | IPC_EXCL | SHMPERM ); // note the vertical bar
/* You MUST call shmget in the parent process before the fork */
Before the shared memory can be used, it must be attached. That is, a pointer reference must be acquired in order
to use it. If the pointers are declared globally, as below, then the parent and all spawned processes will inherit
these pointers and thus can use the shared memory.
volatile char * buff; /* buff [ ] is an array used by parent and all children*/
/* In “pre-fork” parent code: shmat, by default, returns a "void *" Need to cast it to desired type. */
buff = (volatile char*) shmat (segid, 0, 0); // Now all children can access “buff”
Finally, the parent MUST return the shared segment before termination:
rc = shmctl (segid, IPC_RMID, NULL); /*return shared mem*/