您的位置:首页 > 其它

简单的Posix共享内存区程序

2015-06-15 22:28 190 查看
参照《unix 网络编程 卷2》的例子

多个进程同时计数。

环境为centos 6.5  gcc 4.8   glibc  2.12

func.h

#ifndef M_FUNC_H_

#define M_FUNC_H_

/**

*this is some func header

*create by coderguagn

*date 2015/0304

*

* */

#include <sstream>

#include <iostream>

#include <ctime>

using namespace std;

//int to string

static string IntToStr(int value){

stringstream ss;

ss<<value;

return ss.str();

}

static int StrToInt(string value){

int number;

stringstream ss;

ss<<value; //string –>stringstream

ss>>number; //stringstream–>int

return number;

}

//get the time now

static string GetTimeNow(){

char *s;

time_t now;

time(&now);

s=ctime(&now);

string t=s;

return t;

}

//delay

void delay(double sec){

time_t start_time,cur_time;

time(&start_time);

do{

time(&cur_time);

}while(cur_time-start_time<sec);

}

#endif

服务器代码:

#include <iostream>

#include <stdlib.h>

#include <sys/mman.h>

#include <stdio.h>

#include <sys/types.h>

#include <sys/stat.h>

#include <errno.h>

#include <unistd.h>

#include <fcntl.h>

#include <semaphore.h>

using namespace std;

struct shmstruct{

int count;

};

sem_t *m_mutex;

int main(int argc,char **argv){

int fd;

struct shmstruct *ptr;

shm_unlink(“mmregion”);

fd=shm_open(“mmregion”,O_RDWR|O_CREAT|O_EXCL,0644);

if(fd<0)

printf(“create shm fail\n”);

ftruncate(fd,sizeof(shmstruct));

ptr=(shmstruct*)mmap(NULL,sizeof(shmstruct),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

close(fd);

int s=sem_unlink(“shmsemm”);

m_mutex=sem_open(“shmsemm”,O_CREAT|O_EXCL,0644,1);

sem_close(m_mutex);

exit(0);

}

 

客户端代码:

#include <stdlib.h>

#include <stdio.h>

#include <unistd.h>

#include <semaphore.h>//for sem_t

#include <sys/mman.h>

#include <fcntl.h> //for O_RDWR,FILE_MODE

#include <errno.h>

#include <sys/types.h>

#include <sys/stat.h>

#include “Func.h”

struct shmstruct{

int count;

};

sem_t *m_mutex;

int main(int argc,char **argv){

int fd,i,nloop;

pid_t pid;

struct shmstruct *ptr;

nloop=1000;

fd=shm_open(“mmregion”,O_RDWR,0644);

if(fd<0){

printf(“something error when open the region\n”);

}

//int len=sizeof(shmstruct);

ptr=(shmstruct*)mmap(NULL,sizeof(shmstruct),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

//ptr=mmap(NULL,sizeof(shmstruct),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);

close(fd);

m_mutex=sem_open(“shmsemm”,O_RDWR,0644,0);

pid=getpid();

for(i=0;i<nloop;i++){

sem_wait(m_mutex);

printf(“pid %ld:%d\n”,(long)pid,ptr->count++);

sem_post(m_mutex);

delay(1);

}

exit(0);

}

 

注意:编译的时候需要  -lrt   -lpthread 编译参数

先运行服务器程序,然后可以打开多个客户端代码进行测试。

文章作者:coderguang      email:  royalchen@royalchen.com

博客链接:http://blog.royalchen.com

备注:自2015-03-25之后,如无特殊说明,文章均为coderguang原创,转载请注明出处,文章由coderguang保留所有权利。

日期:2015-04-08

 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  共享内存区