LinuxSir.cn,穿越时空的Linuxsir!

 找回密码
 注册
搜索
热搜: shell linux mysql
查看: 914|回复: 4

急!!请大家看一下这个程序

[复制链接]
发表于 2006-3-26 22:34:30 | 显示全部楼层 |阅读模式
#include <stdio.h>
#include <error.h>
#include <stdlib.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <fcntl.h>
#include <string.h>
void quit(char *buf);
int main(void)
{
  system("touch test");
  char path[100];
  int ret;
  getcwd(path,(size_t)(100));
  strcat(path,"/test");
  int fd=open(path,O_RDONLY|O_WRONLY,0644);
  if (fd<0)
      quit("open");
  ret=write(fd,"aaa\n",strlen("aaa\n"));
  if (ret<0)
      quit("write");
  struct stat t;
  ret=fstat(fd,&t);
  if(ret<0)
      quit("fstat");
  long int size=t.st_size;
  char *map=mmap(0,size+strlen ("add\n"),PROT_READ|PROT_WRITE,MAP_SHARED,fd,0);
  if(map==MAP_FAILED)
      quit("mmap");
  printf("%s",map);
  strcat(map,"add\n");
  printf("%s",map);
  close(fd);
  munmap(map,strlen(map));
  exit(EXIT_SUCCESS);
}
void quit(char *buf)
{
    perror("buf");
    exit(EXIT_FAILURE);
}
这个程序在mmap函数处执行失败了,而且显示buf: Permission denied
,请问
1、原因是什么?
2、应如何改正,使之能成功进行内存映像?
3、因为mmap函数返回值是void*类型,是否可以将其强制转换成char*类型,按字符串操作,然后将修改重新写入内存映像即可????
发表于 2006-3-26 22:56:50 | 显示全部楼层
今天刚好写了篇关于mmap的读书笔记,希望有帮助:
http://www.dmwc.org/yy/note/mmap.html

Permission denied的话,难道是文件的打开属性不对?

可以char *map; map=(char*)mmap(....);
回复 支持 反对

使用道具 举报

发表于 2006-3-26 23:50:09 | 显示全部楼层
when you open your test file, just use the O_RDWR flag
回复 支持 反对

使用道具 举报

 楼主| 发表于 2006-3-27 21:43:07 | 显示全部楼层
改后的确好使,请问斑竹可否解释一下什么原因?????
回复 支持 反对

使用道具 举报

发表于 2006-3-27 21:55:29 | 显示全部楼层
O_RDWR != O_RDONLY|O_WRONLY

following pieces from /usr/include/bits/fcntl.h
  1.      31 #define O_RDONLY         00
  2.      32 #define O_WRONLY         01
  3.      33 #define O_RDWR           02
复制代码
回复 支持 反对

使用道具 举报

您需要登录后才可以回帖 登录 | 注册

本版积分规则

快速回复 返回顶部 返回列表