|
|
#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*类型,按字符串操作,然后将修改重新写入内存映像即可???? |
|