Shared memory is the lowest communication mechanism and the fastest communication mechanism in LUnix system. Shared memory uses two or more processes to share the same block of memory to achieve interprocess communication. Typically, a process creates a shared
Memory area, which can then be accessed by multiple processes, where one process will be outgoing data stored in shared memory, and another or more processes will read data directly from shared memory. Thus, this mode of communication is the most efficient way to communicate between processes. The real problem, however, is that when two or more processes use shared memory for communication, the resolution of the synchronization problem is particularly important, or it can cause confusion as different processes read and write data from one shared memory at a time. In the usual case, synchronization of processes is achieved by using semaphores.
The above two programs are an example of interprocess communication. The two programs run separately in different processes and use shared memory for communication. B reads data from the keyboard and is stored in shared memory. A reads the data from shared memory and displays it on the screen. Because no two processes are synchronized, the display will be messy, and the processing of this problem will be done after further learning about synchronization.
The Instance B program is responsible for writing data to shared memory, and a program is responsible for reading out the shared data from memory, and there is no synchronization added between them.
B.c
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include < stdio.h>
#define BUF_SIZE 1024
#define MYKEY
int main ()
{
int shmid;
char *shmptr;
if ((Shmid = Shmget (mykey,buf_size,ipc_creat)) ==-1)
{
printf ("Shmget error \ n");
Exit (1);
}
if ((Shmptr =shmat (shmid,0,0)) = = (void *)-1)
{
printf ("Shmat error!\n");
Exit (1);
}
while (1)
{
printf ("Input:");
scanf ("%s", shmptr);
Exit (0);
}
A.c
#include <stdio.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/ shm.h>
#define BUF_SIZE 1024
#define MYKEY
int main ()
{
int shmid;
char * SHMPTR;
if ((Shmid = Shmget (mykey,buf_size,ipc_creat)) ==-1)
{
printf ("Shmget error!\n");
Exit (1);
}
if ((Shmptr = Shmat (shmid,0,0)) = = (void *)-1)
{
printf ("Shmat error!\n");
Exit (1);
}
while (1)
{
printf ("String:%s\n", shmptr);
Sleep (3);
}
Exit (0);
}
View a full set of articles: Http://www.bianceng.cn/Programming/C/201212/34807.htm