C語(yǔ)言mmap()函數(shù):建立內(nèi)存映射
頭文件:
#include <unistd.h> #include <sys/mman.h>
定義函數(shù):void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offsize);
函數(shù)說(shuō)明:mmap()用來(lái)將某個(gè)文件內(nèi)容映射到內(nèi)存中,對(duì)該內(nèi)存區(qū)域的存取即是直接對(duì)該文件內(nèi)容的讀寫(xiě)。
參數(shù)說(shuō)明:
返回值:若映射成功則返回映射區(qū)的內(nèi)存起始地址,否則返回MAP_FAILED(-1),錯(cuò)誤原因存于errno 中。
錯(cuò)誤代碼:
范例:利用mmap()來(lái)讀取/etc/passwd 文件內(nèi)容。
#include <sys/types.h>#include <sys/stat.h>#include <fcntl.h>#include <unistd.h>#include <sys/mman.h>main(){ int fd; void *start; struct stat sb; fd = open("/etc/passwd", O_RDONLY); /*打開(kāi)/etc/passwd */ fstat(fd, &sb); /* 取得文件大小 */ start = mmap(NULL, sb.st_size, PROT_READ, MAP_PRIVATE, fd, 0); if(start == MAP_FAILED) /* 判斷是否映射成功 */ return; printf("%s", start); munma(start, sb.st_size); /* 解除映射 */ closed(fd);}
執(zhí)行結(jié)果:
root : x : 0 : root : /root : /bin/bashbin : x : 1 : 1 : bin : /bin :daemon : x : 2 : 2 :daemon : /sbinadm : x : 3 : 4 : adm : /var/adm :lp : x :4 :7 : lp : /var/spool/lpd :sync : x : 5 : 0 : sync : /sbin : bin/sync :shutdown : x : 6 : 0 : shutdown : /sbin : /sbin/shutdownhalt : x : 7 : 0 : halt : /sbin : /sbin/haltmail : x : 8 : 12 : mail : /var/spool/mail :news : x :9 :13 : news : /var/spool/news :uucp : x :10 :14 : uucp : /var/spool/uucp :operator : x : 11 : 0 :operator : /root:games : x : 12 :100 : games :/usr/games:gopher : x : 13 : 30 : gopher : /usr/lib/gopher-data:ftp : x : 14 : 50 : FTP User : /home/ftp:nobody : x :99: 99: Nobody : /:xfs :x :100 :101 : X Font Server : /etc/xll/fs : /bin/falsegdm : x : 42 :42 : : /home/gdm: /bin/bashkids : x : 500 :500 :/home/kids : /bin/bash
C語(yǔ)言munmap()函數(shù):解除內(nèi)存映射
頭文件:
#include <unistd.h> #include <sys/mman.h>
定義函數(shù):
int munmap(void *start, size_t length);
函數(shù)說(shuō)明:munmap()用來(lái)取消參數(shù)start 所指的映射內(nèi)存起始地址,參數(shù)length 則是欲取消的內(nèi)存大小。當(dāng)進(jìn)程結(jié)束或利用exec 相關(guān)函數(shù)來(lái)執(zhí)行其他程序時(shí),映射內(nèi)存會(huì)自動(dòng)解除,但關(guān)閉對(duì)應(yīng)的文件描述詞時(shí)不會(huì)解除映射。
返回值:如果解除映射成功則返回0,否則返回-1。錯(cuò)誤原因存于errno 中錯(cuò)誤代碼EINVAL參數(shù) start 或length 不合法。
范例:參考mmap()
新聞熱點(diǎn)
疑難解答
圖片精選