64,683
社区成员
发帖
与我相关
我的任务
分享
#include <pthread.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/shm.h>
#include <errno.h>
#include <stdio.h>
#include <strings.h>
#define err_abort(code,text) do { \
fprintf (stderr, "%s at \"%s\":%d: %s\n", \
text, __FILE__, __LINE__, strerror (code)); \
abort (); \
} while (0)
#define errno_abort(text) do { \
fprintf (stderr, "%s at \"%s\":%d: %s\n", \
text, __FILE__, __LINE__, strerror (errno)); \
abort (); \
} while (0)
key_t shm_key = -1;
int shm_id;
struct INFORMATION
{
int Inf_No;//编号
int Inf_Information;//信息
bool Inf_IsFill;
};
INFORMATION* pShmHead = NULL;
INFORMATION* pShmTail = NULL;
/*共享内存操作*/
bool GetShm(key_t & shm_key,const int &flag)
{
if( (shm_id = shmget(shm_key,sizeof(INFORMATION)*5,IPC_CREAT|IPC_EXCL|flag)) == -1)
{
if(errno == EEXIST)
{
if(shmget(shm_key,sizeof(INFORMATION)*5,flag)>-1)
{
return true;
}
}
err_abort(errno,"Create share memory");
}
return true;
}
bool AttacheShm(key_t& shm_id,const void *shmaddr,const int &flag)
{
if((pShmHead = (INFORMATION*)shmat(shm_id,shmaddr,flag)) == NULL)
err_abort(errno,"Attache share memory");
return true;
}
bool DeacheShm(const void *shmaddr)
{
if(shmdt(shmaddr)==-1)
err_abort(errno,"DeacheShm share memory");
return true;
}
bool RemoveShm(key_t& shm_key)
{
if(shmctl(shm_key, IPC_RMID, NULL) == -1)
err_abort(errno,"RemoveShm share memory");
return true;
}
/*
void * routine(void* arg)
{
INFORMATION* p ;
for(p = pShmHead;p!=pShmTail;p++)
{
printf("%d,%d,%d\n",p->Inf_No,p->Inf_Information,p->Inf_IsFill);
}
DeacheShm(pShmHead);
}
*/
//pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
int main()
{
GetShm(shm_key,0664);
AttacheShm(shm_id,NULL,0);
//pShmTail = pShmHead+5;
//pShmHead->Inf_Information = 0;
//pShmHead->Inf_IsFill = 1;
//pShmHead->Inf_No = 0;
printf("head %p tail %p\n", pShmHead,pShmTail);
//pthread_t thread;
//if(pthread_create(&thread,NULL,routine,NULL)!=0)
// err_abort(errno,"pthread_create");
//pthread_join(thread,NULL);
while(1)
;
//DeacheShm(pShmHead);
}