欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

C語言編程中建立和解除內(nèi)存映射的方法

 更新時(shí)間:2015年08月26日 11:56:50   投稿:goldensun  
這篇文章主要介紹了C語言編程中建立和解除內(nèi)存映射的方法,分別為mmap()函數(shù)和munmap()函數(shù)的使用,需要的朋友可以參考下

C語言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ù)說明:mmap()用來將某個(gè)文件內(nèi)容映射到內(nèi)存中,對該內(nèi)存區(qū)域的存取即是直接對該文件內(nèi)容的讀寫。

參數(shù)說明:

返回值:若映射成功則返回映射區(qū)的內(nèi)存起始地址,否則返回MAP_FAILED(-1),錯(cuò)誤原因存于errno 中。

錯(cuò)誤代碼:

  • EBADF  參數(shù)fd 不是有效的文件描述詞。
  • EACCES  存取權(quán)限有誤。如果是MAP_PRIVATE 情況下文件必須可讀,使用MAP_SHARED 則要有PROT_WRITE 以及該文件要能寫入。
  • EINVAL  參數(shù)start、length 或offset 有一個(gè)不合法。
  • EAGAIN  文件被鎖住,或是有太多內(nèi)存被鎖住。
  • ENOMEM  內(nèi)存不足。

范例:利用mmap()來讀取/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); /*打開/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/bash
bin : x : 1 : 1 : bin : /bin :
daemon : x : 2 : 2 :daemon : /sbin
adm : 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/shutdown
halt : x : 7 : 0 : halt : /sbin : /sbin/halt
mail : 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/false
gdm : x : 42 :42 : : /home/gdm: /bin/bash
kids : x : 500 :500 :/home/kids : /bin/bash

C語言munmap()函數(shù):解除內(nèi)存映射
頭文件:

#include <unistd.h>    #include <sys/mman.h>

定義函數(shù):

int munmap(void *start, size_t length);

函數(shù)說明:munmap()用來取消參數(shù)start 所指的映射內(nèi)存起始地址,參數(shù)length 則是欲取消的內(nèi)存大小。當(dāng)進(jìn)程結(jié)束或利用exec 相關(guān)函數(shù)來執(zhí)行其他程序時(shí),映射內(nèi)存會自動解除,但關(guān)閉對應(yīng)的文件描述詞時(shí)不會解除映射。

返回值:如果解除映射成功則返回0,否則返回-1。錯(cuò)誤原因存于errno 中錯(cuò)誤代碼EINVAL參數(shù) start 或length 不合法。

范例:參考mmap()

相關(guān)文章

最新評論