-
#include<sys/mman.h>
-
#include<stdio.h>
-
#include<stdlib.h>
-
#include<unistd.h>
-
#include<errno.h>
-
#include<string.h>
-
#include<fcntl.h>
-
#include<pthread.h>
-
#include<assert.h>
-
#include<sys/types.h>
-
#include<sys/stat.h>
-
#include<signal.h>
-
-
struct sh_mem{
-
pthread_mutex_t mutex;
-
int val;
-
};
-
-
int main(int argc, char *argv[])
-
{
-
int pid;
-
int nloop;
-
struct sh_mem *ptr;
-
int fd;
-
int ret;
-
-
#ifndef _POSIX_THREAD_PROCESS_SHARED
-
fprintf(stderr," Not define _POSIX_THREAD_PROCESS_SHARED");
-
exit(-1);
-
#endif
-
-
if(argc != 3){
-
fprintf(stderr, "Usage: you need three paremter\n");
-
exit(EXIT_FAILURE);
-
}
-
-
nloop = atoi(argv[2]);
-
-
fd = open(argv[1], O_RDWR | O_CREAT, 0644);
-
ret = ftruncate(fd,sizeof(int));
-
if(fd == -1){
-
fprintf(stderr, "open error: %s\n", strerror(errno));
-
exit(-1);
-
}
-
-
ptr = mmap(NULL, sizeof(struct sh_mem), PROT_READ | PROT_WRITE, MAP_SHARED, fd, 0);
-
if(ptr == MAP_FAILED){
-
fprintf(stderr, " mmap failed %s \n", strerror(errno));
-
exit(EXIT_FAILURE);
-
}
-
close(fd);
-
ptr->val = 0;
-
-
-
int pshared = PTHREAD_PROCESS_SHARED;
-
pthread_mutexattr_t attr;
-
-
ret = pthread_mutexattr_init( &attr );
-
if(ret != 0){
-
fprintf(stderr, "pthread_mutexattr_init() error: %s\n" ,strerror(errno));
-
exit(-1);
-
}
-
-
ret = pthread_mutexattr_setpshared( &attr, pshared);
-
if(ret != 0){
-
fprintf(stderr, "pthread_mutexattr_setpshared() error: %s\n" ,strerror(errno));
-
exit(-1);
-
}
-
-
ret = pthread_mutexattr_getpshared( &attr, &pshared);
-
if(ret != 0){
-
fprintf(stderr, "pthread_mutexattr_getpshared() error: %s\n" ,strerror(errno));
-
exit(-1);
-
}
-
assert(pshared == PTHREAD_PROCESS_SHARED);
-
-
ret = pthread_mutex_init( &(ptr->mutex), &attr);
-
assert(ret == 0);
-
-
ret = pthread_mutexattr_destroy(&attr);
-
assert(ret == 0);
-
-
int i;
-
signal(SIGCHLD, SIG_IGN);
-
pid = fork();
-
assert(pid >=0);
-
-
if(pid == 0){
-
for(i=0; i<nloop; i++){
-
pthread_mutex_lock(&ptr->mutex);
-
ptr->val++;
-
printf("Child process: %d\n", ptr->val);
-
pthread_mutex_unlock(&ptr->mutex);
-
}
-
return 0 ;
-
}
-
for(i=0; i<nloop; i++){
-
pthread_mutex_lock(&ptr->mutex);
-
ptr->val++;
-
printf("Main process: %d\n", ptr->val);
-
pthread_mutex_unlock(&ptr->mutex);
-
}
-
return 0;
-
}
这个代码是一个测试性的代码,有几点需要注意的地方:
1、采用的是pthread_mutex_t mutex 和mmap实现的数据同步和共享
2、mutex属性必须设置为进程共享的
3、open一个文件作为内存映射过后,必须对该问价设置大小,或者是通过fd向该文件写入一些数据,再做mmap映射,不然会出现总线错误。原因应该是open创建的文件大小是0,映射到地址空间过后不可用