/*sharemem_write.c*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#include <sys/sem.h>
#define SHARE_SIZE 2048
union semun
{
int val; /* value for SETVAL */
struct semid_ds *buf; /* buffer for IPC_STAT, IPC_SET */
unsigned short *array; /* array for GETALL, SETALL */
/* Linux specific part: */
struct seminfo *__buf; /* buffer for IPC_INFO */
};
int sem_creat()
{
int semid;
semid=semget((key_t)8972,1,IPC_CREAT|0666);
return semid;
}
void sem_setval(int semid)
{
union semun semun_info;
semun_info.val=1;
semctl(semid,0,SETVAL,semun_info);
}
void sem_p(int semid)
{
struct sembuf sem_buf;
sem_buf.sem_num=0;
sem_buf.sem_op=-1;
sem_buf.sem_flg=SEM_UNDO;
semop(semid,&sem_buf,1);
}
void sem_v(int semid)
{
struct sembuf sem_buf;
sem_buf.sem_num=0;
sem_buf.sem_op=1;
sem_buf.sem_flg=SEM_UNDO;
semop(semid,&sem_buf,1);
}
struct student
{
char name[30];
int age;
};
int main(int argc,char *argv[])
{
int shmid;
int semid;
int i=0;
struct student *stu_info;
void *shm_addr=NULL;
//semid=sem_creat();
shmid=shmget((key_t)5566,SHARE_SIZE,IPC_CREAT|0666);
shm_addr=shmat(shmid,NULL,0);
stu_info=(struct student*)shm_addr;
strcpy(stu_info->name,"cn0803 hzq");
//sem_p(semid);
stu_info->age++;
printf("stu age %d\n",stu_info->age);
sleep(1);
stu_info->age++;
printf("stu age %d\n",stu_info->age);
sleep(1);
//sem_v(semid);
return 0;
}
/*sharememe_read.c*/
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#define SHARE_SIZE 2048
struct student
{
char name[30];
int age;
};
int main(int argc,char *argv[])
{
int shmid;
struct student *stu_info;
void *shm_addr=NULL;
shmid=shmget((key_t)5566,SHARE_SIZE,IPC_CREAT|0666);
shm_addr=shmat(shmid,NULL,0);
stu_info=(struct student*)shm_addr;
printf("student name %s\n",stu_info->name);
shmdt(shm_addr);
shmctl(shmid,IPC_RMID,NULL);
return 0;
}