创建共享内存,但是在读共享内存之前,该共享内存不会被删除
#include <stdio.h>
#include <sys/types.h>#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int shmid;
void sig_handler(int sig)
{
int res = shmctl(shmid,IPC_RMID,0);
if(res == -1) perror("shmctl"),exit(-1);
printf("共享内存关闭 FROM ysd|\n");
exit(0);
}
int main(int argc,char* argv[])
{
if(signal(SIGINT,sig_handler) == SIG_ERR)
{
perror("signal"),exit(-1);
}
key_t key = ftok(".",200);
if(shmid == -1)
perror("ftok"),exit(-1);
shmid = shmget(key,4096,IPC_CREAT|IPC_EXCL|0600);
if(-1 == shmid)
perror("shmget"),exit(-1);
void* p = shmat(shmid,0,0);
if(p == (void*)-1)
perror("shmat"),exit(-1);
memset(p,0,4096);
strcpy(p,"hello,world");
int res = shmdt(p);
if(res == -1)
perror("shmdt"),exit(-1);
while(1);
return 0;
}
读共享内存.
#include <stdio.h>
#include <sys/types.h>
#include <unistd.h>
#include <fcntl.h>
#include <sys/stat.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <signal.h>
#include <errno.h>
#include <string.h>
#include <stdlib.h>
int main(int argc,char* argv[])
{
key_t key = ftok(".",200);
if(key == -1) perror("key"),exit(-1);
int shmid = shmget(key,0,0);
void* p = shmat(shmid,0,0);
printf("%s\n",(char*)p);
shmdt(p);
return 0;
}