C语言整理之共享内存

C语言之共享内存

ShareMemory1.c

#include

#include

#include

#include

#include

#include

#include

 

#define SHMKEY   1111

#define SHMSIZE  4096

 

int main()

{

int shmid,ret,count = 0;

void *shmaddr;

 

shmid = shmget(SHMKEY,SHMSIZE,IPC_CREAT | IPC_EXCL);

if(-1 == shmid)

{

perror("shmget");

exit(1);

}

 

shmaddr = shmat(shmid,NULL,0);

if((void *)-1 == shmaddr)

{

perror("shmat");

exit(1);

}

 

*(int *)shmaddr = count;

 

while(1)

{

count = *(int *)shmaddr;

usleep(100000);

printf("Process1 : count = %d\n",count);

count++;

if(count > 101)

{

break;

}

*(int *)shmaddr = count;

}

 

ret = shmdt(shmaddr);

if(-1 == ret)

{

perror("shmdt");

exit(1);

}

 

ret = shmctl(shmid,IPC_RMID,NULL);

if(-1 == ret)

{

perror("shmctl");

exit(1);

}

return 0;

}

 

 

 

ShareMemory4.c

#include

#include

#include

#include

#include

#include

#include

 

#define SHMKEY   1111

#define SHMSIZE  4096

 

int main()

{

int shmid,ret,count = 0;

void *shmaddr;

 

shmid = shmget(SHMKEY,SHMSIZE,0);

if(-1 == shmid)

{

perror("shmget");

exit(1);

}

 

shmaddr = shmat(shmid,NULL,0);

if((void *)-1 == shmaddr)

{

perror("shmat");

exit(1);

}

 

//*(int *)shmaddr = count;

 

while(1)

{

count = *(int *)shmaddr;

usleep(100000);

printf("Process2 : count = %d\n",count);

count++;

if(count > 101)

{

break;

}

*(int *)shmaddr = count;

}

 

ret = shmdt(shmaddr);

if(-1 == ret)

{

perror("shmdt");

exit(1);

}

 

/*ret = shmctl(shmid,IPC_RMID,NULL);

if(-1 == ret)

{

perror("shmctl");

exit(1);

}*/

return 0;

}

 

 

你可能感兴趣的:(C语言整理之共享内存)