#include <stdio.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
key_t key =ftok("./",29);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key %#x\n",key);
//创建共享内存
int shmid =shmget(key,32,IPC_CREAT|0777);
if(shmid < 0)
{
perror("shmget");
return -1;
}
printf("shmid = %d\n",shmid);
//映射到当前进程上
void *shmaddr =shmat(shmid,NULL,0);
if((void*)-1==shmaddr)
{
perror("shmat");
return -1;
}
printf("shmaddr %p\n",shmaddr);
char *pa=(char*)shmaddr;
*pa=0;
char *arr=pa+1;
strcpy(arr,"123456");
while(1)
{
if(0==*pa)
{
printf("%s\n",arr);
sleep(1);
*pa=1;
}
}
system("ipcs -m");
return 0;
}
#include <stdio.h>
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, const char *argv[])
{
key_t key =ftok("./",29);
if(key < 0)
{
perror("ftok");
return -1;
}
printf("key %#x\n",key);
//创建共享内存
int shmid =shmget(key,32,IPC_CREAT|0777);
if(shmid < 0)
{
perror("shmget");
return -1;
}
printf("shmid = %d\n",shmid);
//映射到当前进程上
void *shmaddr =shmat(shmid,NULL,0);
if((void*)-1==shmaddr)
{
perror("shmat");
return -1;
}
char *pa=(char*)shmaddr;
char *i,*j,temp;
while(1)
{
i=pa+1;
j= i+strlen(i)-1;
if(*pa==1)
{
while(i<j)
{
temp=*i;
*i=*j;
*j=temp;
i++;
j--;
}
*pa=0;
}
}
//system("ipcs -m");
//shmdt(shmaddr);
return 0;
}