#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdio.h>
#include <stdlib.h>
int main()
{
int shmid;
char *shmadd;
struct shmid_ds shmbuf;
if((shmid=shmget(IPC_PRIVATE,1000,0666))<0)
{perror("shmget");exit(1);}
else printf("created shared-memory: %d\n",shmid);
system("ipcs -m");
if((shmadd=shmat(shmid,0,0))<(char *)0)
{ perror("shmat");exit(1); }
else printf("attached shared-memory\n");
system("ipcs -m");
if((shmdt(shmadd))<0) //禁止本进程再使用该共享内存区
{perror("shmdt");exit(1);}
else printf("deleted shared-memory\n");
system("ipcs -m");
if(shmctl(shmid,IPC_RMID,&shmbuf)<0)
{perror("shmctl");exit(1);}
system("ipcs -m");
return 0;
}
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
typedef struct
{
char name;
int age;
}people;
int main(int argc,char **argv)
{
int shm_id,i;
key_t key;
char temp_char;
people *p_map;
shm_id=shmget(IPC_PRIVATE,4096,IPC_CREAT);
if(shm_id<0)
{perror("shmget error");return;}
p_map=(people*)shmat(shm_id,NULL,0);
temp_char='a';
for(i=0;i<10;i++)
{
(*(p_map+i)).name=temp_char;
(*(p_map+i)).age=20+i;
temp_char+=1;
}
if(shmdt(p_map)<0)
perror("detach error");
return 0;
}
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
typedef struct
{
char name;
int age;
}people;
int main(int argc,char **argv)
{
int shm_id,i;
key_t key;
people *p_map;
struct shmid_ds shmbuf;
shm_id=393216;//393216是ipcs -m查看到的shmid
p_map=(people*)shmat(shm_id,NULL,0);
for(i=0;i<10;i++)
{
printf("name----------%c\n",(*(p_map+i)).name);
printf("age------------%d\n",(*(p_map+i)).age);
}
if(shmdt(p_map)<0)
perror("shmdt error");
if(shmctl(shm_id,IPC_RMID,&shmbuf)<0)
perror("shmctl error");
return 0;
}
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
typedef struct
{
char name;
int age;
}people;
int main(int argc,char **argv)
{
int shm_id,i;
key_t key;
char temp_char;
people *p_map;
char *name="/dev/shm/myshm1";
key = ftok(name,0);
printf("key=%d\n",key);
if(key==-1)
perror("ftok error");
shm_id=shmget(IPC_PRIVATE,4096,IPC_CREAT);
printf("shm_id=%d\n",shm_id);
if(shm_id==-1)
{perror("shmget error");return;}
p_map=(people*)shmat(shm_id,NULL,0);
temp_char='a';
for(i=0;i<10;i++)
{
(*(p_map+i)).name=temp_char;
temp_char+=1;
(*(p_map+i)).age=20+i;
}
if(shmdt(p_map)==-1)
perror("detach error");
return 0;
}
#include <sys/shm.h>
#include <sys/types.h>
#include <unistd.h>
typedef struct
{
char name;
int age;
}people;
int main(int argc,char **argv)
{
int shm_id,i;
key_t key;
people *p_map;
char *name="/dev/shm/myshm1";
key = ftok(name,0);
if(key==-1)
perror("ftok error");
shm_id=shmget(key,4096,IPC_CREAT);
printf("shm_id=%d\n",shm_id);
if(shm_id==-1)
{perror("shmget error");return;}
p_map=(people*)shmat(shm_id,NULL,0);
p_map=(people*)shmat(393216,NULL,0);
for(i=0;i<10;i++)
{
printf("name----------%c\n",(*(p_map+i)).name);
printf("age-----------%d\n",(*(p_map+i)).age);
}
if(shmdt(p_map)==-1)
perror("detach error");
return 0;
}