3.11共享内存编程实现(第二阶段)
shmr.c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
// int shmget(key_t key, size_t size, int shmflg);
// void *shmat(int shmid, const void *shmaddr, int shmflg);
// void *shmat(int shmid, const void *shmaddr, int shmflg);
// int shmctl(int shmid, int cmd, struct shmid_ds *buf);
int main()
{
int shmid;
char *shmaddr;
key_t key;
key = ftok(".",1);
shmid = shmget(key,1024*4,0);
if(shmid == -1){
printf("shmget failed\n");
exit(-1);
}
shmaddr = shmat(shmid,0,0);
printf("shmat ok\n");
printf("data: %s\n",shmaddr);
shmdt(shmaddr);
printf("quit\n");
return 0;
}
shmw.c
#include <sys/ipc.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <sys/types.h>
#include <stdio.h>
#include <string.h>
// int shmget(key_t key, size_t size, int shmflg);
// void *shmat(int shmid, const void *shmaddr, int shmflg);
// void *shmat(int shmid, const void *shmaddr, int shmflg);
// int shmctl(int shmid, int cmd, struct shmid_ds *buf);
int main()
{
int shmid;
char *shmaddr;
key_t key;
key = ftok(".",1);
shmid = shmget(key,1024*4,IPC_CREAT|0666);
if(shmid == -1){
printf("shmget failed\n");
exit(-1);
}
shmaddr = shmat(shmid,0,0);
printf("shmat ok\n");
strcpy(shmaddr,"chenlichen");
sleep(5);
shmdt(shmaddr);
shmctl(shmid,IPC_RMID,0);
printf("quit\n");
return 0;
}