进程间通信之共享内存
-
创建共享内存,写进程每隔2秒向内存写入一次“hello world”;
如果结束写操作,则写进程写入“end”; -
读进程从共享内存读取数据,并打印。直到读到“end”为止。
这是写进程
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#define SIZE 2048
typedef struct{
char xinxi[20];
} xx;
int main()
{
xx *point;
key_t key;
key = ftok(".",6);
int shmid;
if ((shmid = shmget (key,SIZE,IPC_CREAT)) <0 ) { perror("shmget"); exit (1); }
else
printf ("creat ok,shmid is :%d \n",shmid);
point = (xx*)shmat(shmid,0,0);
char sc[3]="a";
char yes[3] = "y";
int n=1,i=0;
for (n = 1; n >= 1;)
{
printf ("是否结束写操作? \n");
sc