getshm.c

来自「多用户银行系统」· C语言 代码 · 共 126 行

C
126
字号
#include "../include/structs.h"#include "../include/stddef.h"#include <sys/types.h>#include <signal.h>#include <stdio.h>#include <sys/ipc.h>#include <unistd.h>#include <sys/shm.h> #include <sys/sem.h>union semun{	int val;	struct semid_ds *buf;	unsigned short int *array;};void * getSHM();int main(int argc,char**argv){	SHM *shm;	int shm_id;	int i;	int key;	int p;	char *name = "/dev/shm/myshm2";	int sem_id;	union semun options;	struct sembuf lock_it;	//shm = (SHM*)malloc(sizeof(SHM));	key = ftok(name,0);	//i = (int *)malloc(sizeof(int));	if(key == -1){		perror("ftok error\n");	}	printf("111111");	shm_id = shmget(key,1024,IPC_CREAT);		sem_id = semget(key,1,IPC_CREAT|0666);	printf("sem_id=%d\n",sem_id);	printf("shm_id=%d\n",shm_id);	printf("1111111111\n");	if(-1 == sem_id ){		printf("create semaphore error\n");		exit(-1);	}	options.val = 0;		printf("111111111111\n");	semctl(sem_id,0,SETVAL,options);	i = semctl(sem_id,0,GETVAL,0);	printf("%d\n",i);	lock_it.sem_num = 0;	lock_it.sem_op = -1;	lock_it.sem_flg = IPC_NOWAIT;		printf("xiu gai hou de %d\n",i);//	shm_id = shmget(key,1024,IPC_CREAT|0666);	if(shm_id == -1){		perror("shmget error\n");		return;	}	printf("3333333333333\n");	/*p = getSHM();	printf("aaaa%d\n",p);	shm = p;	shm->inta  = 20; 	printf("%d\n",shm);	printf("%d\n",shm->inta);	//(SHM*)getSHM();	*/	shm = (SHM*)getSHM();	/*	lock_it.sem_num = 0;	lock_it.sem_op = +1;	lock_it.sem_flg = IPC_NOWAIT;	semop(sem_id,&lock_it,1);*/		i = semctl(sem_id,0,GETVAL,0);	printf("de dao hou xiu gai = %d\n",i); 	//shm -> inta = 20;	//printf("%d\n",shm->inta);	shm->inta = 20;	printf("%d\n",shm->inta);}void * getSHM(){	//int *i;	void *p;	//i = (int *)malloc(sizeof(int));	int shm_id;	int sem_id;	union semun options;	struct sembuf lock_it;	int key;	char *name = "/dev/shm/myshm2";	//SHM * p;	key = ftok(name,0);	shm_id = shmget(key,0,0);	sem_id = semget(key,0,0);		semctl(sem_id,0,SETVAL,options);	//*i = semctl(sem_id,0,GETVAL,0);	p = shmat(shm_id,NULL,0);	*((int *)p) = semctl(sem_id,0,GETVAL,0);	printf("%d\n",*((int *)p));	//i = (int *)malloc(sizeof(int));	while(1){		if(*((int *)p)==0){		//	p = i+sizeof(int);		//	p = (SHM*)malloc(sizeof(SHM));			//	printf("%d\n",i);		//	return (p);				//*i = 1;			p = p+sizeof(int);			*((int*)p) = 1;			printf("%d\n",p);			return ((void *)p);		}		else{			p = p+sizeof(int)+sizeof(SHM);			continue;					}	}}

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?