简单的Posix共享内存区程序

参照《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

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值