概念:共享内存是IPC机制的一种,雨荨两个不相关的进程访问同一段内存,也是传递数据一种非常有效的方式。
共享内存---------写
#include<sys/types.h>
#include<sys/shm.h>
#include<sys/ipc.h>
#include<stdio.h>
#include<unistd.h>
#include<stdlib.h>
#define TEXT_SZ 2048
struct shared_use_st
{
int written_by_you;
char some_text[TEXT_SZ];
}
int main()
{
int running=1;
int shmid;
char buffer[TEXT_SZ];
struct shared_use_st *shared_stuff;
//1创建内存
shmid = shmget((key_t)1234, sizeof(struct shared_use_st), IPC_CREAT)
if(shmid==-1)
{
printf("creat shared memory failed");
exit(EXIT_FAILURE);
}
//2映射内存
shared_stuff= (struct shared_use_st*)shmat( shmid, NULL,0);
//3循环
while(running)
{
while(shared_stuff->written_by_you=1)
(
sleep(1);
printf("wait read\n");
)
//3.1用户输入
fgets(buffer,TEXT_SIZE,stdin);
}
//3.2将输入字符放入共享内存
styncpy(shared_stuff->some_text,buffer,TEXT_SZ);
shared_stuff->written_by_you=1;
if(strncmp(buffer,"end",3)==0)
running=0;
//4脱离共享内存
shmdt(( const void *)shared_stuff);
return 1;
}
共享内存--------读