Sharing memory among a parent and child process in Solaris (in C)
I am just looking for a simple tutorial/example to put me in the right direction, I cannot seem to find a good simpl开发者_运维问答e one.
I am looking for a tutorial that explains how to share memory (not using pipes and files, but actual memory) between a parent and a child (using fork) process in UNIX (Solaris) in C.
I really appreciate your help,
Thank you very much,
Jary
You have to options:
You can allocate and attach the shared memory first and then do the fork.
You can allocate the shared memory, fork the child process and then attach to the shared memory in both processes.
The first option is probably easier. It could look as follows:
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
....
int size = 32000;
/* allocate and attach shared memory */
int shmID = shmget(IPC_PRIVATE, size, 0600);
void* shmPtr = shmat(shmId, NULL, 0);
/* fork child process */
pid_t pID = fork();
if (pID == 0)
{
/* child */
... do something with shmPtr ...
/* detach shared memory */
shmdt(shmPtr);
}
else
{
/* parent */
... do something with shmPtr ...
/* detach shared memory */
shmdt(shmPtr);
}
精彩评论