MMap 函数
#include <sys/mman.h>
void *mmap(void *addr, size_t len, int prot, int flags,int fildes, off_t off);
The mmap() function shall establish a mapping between the address space of the process at an address pa forlen bytes to the memory object represented by the file descriptor fildes at offset off for len bytes.The value of pa is an implementation-defined function of the parameter addr and the values of flags, furtherdescribed below. A successful mmap() call shall return pa as its result. The address range starting at pa andcontinuing for len bytes shall be legitimate for the possible (not necessarily current) address space of the process.……哥英文不太好,来自http://www.opengroup.org/onlinepubs/000095399/functions/mmap.html看不懂……
总之,mmap函数把一个文件的内容在内存里面做一个映像。于是可以用mmap和/dev/zero来分配内存。为指针分配内存效果应该和malloc差不多。帖个小程序:
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <unistd.h>
#include <sys/file.h>
#include <sys/mman.h>
#include <string.h>
int main(int argc, char** argv) {
struct tms *a;
clock_t b;
long int c;
int fd=open("/dev/zero",O_RDWR);
a=mmap(0,sizeof(struct tms),PROT_READ|PROT_WRITE,MAP_PRIVATE,fd,0);
sleep(2);
b=times(a);
c=sysconf(_SC_CLK_TCK);
printf("The user time is %d\nThe sys time is %d\n ",(int)a->tms_utime,(int)a->tms_stime);
printf("The all time is %d \n",(int)b);
printf("The f is %d\n",c);
return (EXIT_SUCCESS);
}
sysconf(_SC_CLK_TCK)返回内核创建时的时钟频率,times()将返回过去一段时间时钟滴答的次数。用mmap分配内存地址当然可以用malloc来代替……
最新评论