Skip to content

Instantly share code, notes, and snippets.

@liuxinglanyue
Last active August 29, 2015 14:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liuxinglanyue/cbafc29c120ccdd04924 to your computer and use it in GitHub Desktop.
Save liuxinglanyue/cbafc29c120ccdd04924 to your computer and use it in GitHub Desktop.
//attach_shm.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#define BUFSZ 1024
int main()
{
int *shm;
shm = shmat(131072,NULL,0);
if(*shm == -1){
printf("shmat failed\n");
return -1;
}
printf("attach shared memory succeed: %d\n",*shm);
system("ipcs -m"); //查看共享内存调用状态
if(shmdt(shm) == -1){
printf("shmdt failed\n");
return -1;
}
system("ipcs -m"); //查看共享内存调用状态
return 0;
}
//create_shm.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
#define BUFSZ 1024
int main()
{
int shm_id; //共享内存ID
shm_id = shmget(IPC_PRIVATE,BUFSZ,0666);
if(shm_id < 0){
printf("shmget failed\n");
return -1;
}
printf("create shared memory succeed: %d\n",shm_id);
system("ipcs -m"); //查看共享内存ID
return 0;
}
//read_shm.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
typedef struct
{
char name[4];
int age;
}people;
int main()
{
int i;
char *t = 'a';
people *p_shm = NULL;
p_shm = shmat(131072,NULL,0);
if(p_shm == NULL){
printf("shmat failed\n");
return -1;
}
for(i=0;i<5;i++) {
printf("name:%s age:%d\n",(*(p_shm+i)).name,(*(p_shm+i)).age);
}
if(shmdt(p_shm) == -1){
printf("shmdt failed\n");
return -1;
}
return 0;
}
//attach_shm.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
int main()
{
shmctl(131072, IPC_RMID, NULL);
return 0;
}
//write_shm.c
#include<sys/types.h>
#include<sys/ipc.h>
#include<sys/shm.h>
#include<stdio.h>
typedef struct
{
char name[4];
int age;
}people;
int main()
{
int i;
char *t = 'a';
people *p_shm = NULL;
p_shm = shmat(131072,NULL,0);
if(p_shm == NULL){
printf("shmat failed\n");
return -1;
}
for(i=0;i<5;i++) {
t += 1;
memcpy((*(p_shm+i)).name,&t,1);
(*(p_shm+i)).age = 20+i;
}
if(shmdt(p_shm) == -1){
printf("shmdt failed\n");
return -1;
}
return 0;
}
@liuxinglanyue
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment