写1234567890
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include<sys/sem.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main()
{
int shmid = shmget(0x111,2000,IPC_CREAT|0777);
if(shmid==-1)
{
perror("shm\n");
return -1;
}
char*addres = (char*)shmat(shmid,NULL,0);
int semid = semget(0x222,1,IPC_CREAT|0777);
if(semid==-1)
{
perror("semget\n");
return -1;
}
struct sembuf p={0,-1,0};
struct sembuf v={0,+1,0};
int count=0;
while(count<101)
{
semop(semid,&p,1);
strcat(addres,"0123456789");
usleep(1000);
semop(semid,&v,1);
count++;
}
shmdt(addres);
}
写----------
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include<sys/sem.h>
#include<stdio.h>
#include<unistd.h>
#include<string.h>
int main()
{
int shmid = shmget(0x111,2000,IPC_CREAT|0777);
if(shmid==-1)
{
perror("shm\n");
return -1;
}
char*addres = (char*)shmat(shmid,NULL,0);
int semid = semget(0x222,1,IPC_CREAT|0777);
if(semid==-1)
{
perror("semget\n");
return -1;
}
struct sembuf p={0,-1,0};
struct sembuf v={0,+1,0};
int count=0;
while(count<101)
{
semop(semid,&p,1);
strcat(addres,"----------");
usleep(1000);
semop(semid,&v,1);
count++;
}
shmdt(addres);
}
读共享内存的内容
#include <sys/ipc.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <sys/sem.h>
#include<stdio.h>
#include<unistd.h>
int main()
{
int shmid = shmget(0x111,2000,IPC_CREAT|0777);
if(shmid==-1)
{
perror("shm\n");
return -1;
}
int semid = semget(0x222,1,IPC_CREAT|0777);
if(semid==-1)
{
perror("semget\n");
return -1;
}
char*addres = (char*)shmat(shmid,NULL,0);
printf("%s\n",addres);
shmdt(addres);
shmctl(shmid,IPC_RMID,NULL);
semctl(semid,0,IPC_RMID);
}