这段用 mmap 读取的代码有什么问题?
whats wrong with this code of reading with mmap?
我正在尝试 运行 此代码,而我以 -
值:1
值:0.000000
我的问题是为什么两个结果不同?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
int main ()
{
int fd;
struct stat mystat;
void *pmap;
int i,integer;
double *values;
int32_t *mapped_baseA;
int32_t fdA;
fd = open("test.txt",O_RDWR); // a text file containing- 1 2 3 4 5
if(fd==-1)
{
perror("open");
exit(1);
}
if(fstat(fd,&mystat)<0)
{
perror("fstat");
close(fd);
exit(1);
}
pmap = mmap(0,mystat.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
if(pmap==MAP_FAILED)
{
perror("mmap failed");
close(fd);
exit(1);
}
//strncpy(pmap,"That is my name",15);
sscanf (pmap, " %d", &integer);
printf("value: %d \n", integer);
//从字符串扫描后打印值。
values = (double *) mmap(0,mystat.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
printf("value: %lf \n", values[1]);
//打印指针的值
munmap (pmap, mystat.st_size);
close(fd);
return 0;
}
仔细阅读(和几次次)mmap(2)。注意:
A file is mapped in multiples of the page size.
并在 ERRORS
部分
EINVAL
We don't like addr, length, or offset (e.g., they are too
large, or not aligned on a page boundary).
考虑在您的可执行文件上也使用 strace(1)。
当然,内存映射只是将映射文件的视图(作为字节的原始序列)提供给该视图部分的process by modifying its virtual address space. It obviously won't do any conversion (you might use sscanf(3) or strtol(3)将数字的 UTF8 或 ASCII 字符串表示形式转换为其机器表示形式)。
我正在尝试 运行 此代码,而我以 - 值:1 值:0.000000
我的问题是为什么两个结果不同?
#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/mman.h>
#include <string.h>
#include <unistd.h>
int main ()
{
int fd;
struct stat mystat;
void *pmap;
int i,integer;
double *values;
int32_t *mapped_baseA;
int32_t fdA;
fd = open("test.txt",O_RDWR); // a text file containing- 1 2 3 4 5
if(fd==-1)
{
perror("open");
exit(1);
}
if(fstat(fd,&mystat)<0)
{
perror("fstat");
close(fd);
exit(1);
}
pmap = mmap(0,mystat.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
if(pmap==MAP_FAILED)
{
perror("mmap failed");
close(fd);
exit(1);
}
//strncpy(pmap,"That is my name",15);
sscanf (pmap, " %d", &integer);
printf("value: %d \n", integer);
//从字符串扫描后打印值。
values = (double *) mmap(0,mystat.st_size,PROT_READ | PROT_WRITE,MAP_SHARED,fd,0);
printf("value: %lf \n", values[1]);
//打印指针的值 munmap (pmap, mystat.st_size);
close(fd);
return 0;
}
仔细阅读(和几次次)mmap(2)。注意:
A file is mapped in multiples of the page size.
并在 ERRORS
部分
EINVAL
We don't like addr, length, or offset (e.g., they are too large, or not aligned on a page boundary).
考虑在您的可执行文件上也使用 strace(1)。
当然,内存映射只是将映射文件的视图(作为字节的原始序列)提供给该视图部分的process by modifying its virtual address space. It obviously won't do any conversion (you might use sscanf(3) or strtol(3)将数字的 UTF8 或 ASCII 字符串表示形式转换为其机器表示形式)。