#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>
#include <pthread.h>
#define SHM_PATH "."
typedef struct data
{
int shmid;
int flag;
int datasize;
char data[1024];
}Data,*PData;
static void * task(void * arg)
{
Data* d = NULL;
int shmid = -1;
if(arg == NULL)
{
printf("task arg is NULL \n");
return NULL;
}
shmid = *((int *)arg);
printf("task start ... \n");
d =(Data *)shmat(shmid,NULL,0);
//d = (Data *)arg;
while(1)
{
if(d->flag == 1)
{
printf(" task data size %d info %s \n",d->datasize,d->data);
if(strncmp("quit",d->data,4) == 0)
{
break;
}else{
memset(d->data,0,1024);
sprintf(d->data,"This is return message : %s \n","eeeeeeeeeee");
}
d->flag = 0;
}
printf("task wait data ...\n");
sleep(1);
}
printf("task exit ... \n");
}
static void * task1(void * arg)
{
Data* data;
int shmid = -1;
char * p = NULL;
if(arg == NULL)
{
printf("task1 arg is nULL \n");
return NULL;
}
shmid = *((int *)arg);
data = (PData)shmat(shmid,NULL,0);
printf("task1 start ... \n");
while(1)
{
if(data->flag == 0)
{
printf("task1 recv data : %s \n",data->data);
if((p = fgets(data->data,1024,stdin)) != NULL)
{
printf("task1 %s \n",data->data);
data->flag = 1;
}
if(strncmp("quit",data->data,4) == 0)
{
printf("task1 quit ... \n");
break;
}
}
usleep(1000);
}
}
int main(int argc, char const *argv[])
{
pthread_t stid,wtid;
key_t key;
int shmid = -1;
int retval = -1;
struct shmid_ds shminfo;
void * r;
PData data;
printf("hello wrold\n");
key = ftok(SHM_PATH,0);
if(key < 0)
{
perror("ftok failed \n");
}
shmid = shmget(key,sizeof(Data) * 10,IPC_CREAT | 0600);// get share memory key
if(shmid < 0)
{
perror("shmget :");
exit(0);
}
r = shmat(shmid,NULL,0); // map key
if(r == NULL)
{
perror("shmat : ");
exit(0);
}
data = (PData)r;
memset(data,0,sizeof(Data)*10);
data->shmid = shmid;
retval = shmctl(shmid,IPC_STAT,&shminfo); // get share memory info e.g: pid uid write or read?
if(retval < 0)
{
perror("shmctl :");
exit(0);
}
printf("share memory create pid : %d ,current pid : %d \n",shminfo.shm_cpid,getpid());
if(data != NULL)
retval = shmdt((void *)data); // Just only disconnect,not delete share memory
if(retval < 0)
{
perror("shmdt : ");
exit(0);
}
retval = pthread_create(&stid,NULL,(void *)&task,(void *)&shmid);
if(retval < 0){
printf("task create failed \n");
exit(0);
}
retval = pthread_create(&wtid,NULL,(void *)&task1,(void *)&shmid);
if(retval <0)
{
printf("task1 create failed \n");
exit(-1);
}
printf("stid : %ld,wtid : %ld \n",stid,wtid);
pthread_join(stid,NULL);
pthread_join(wtid,NULL);
printf("main eixt ... \n");
return 0;
}
共享内存使用-linux应用
最新推荐文章于 2024-09-02 10:20:11 发布