Linux 的mmap问题球解答?
//完成图书信息的录入#include<ncurses.h>#include<sys/mman.h>#include<unistd.h>#include<fcntl.h>...
//完成图书信息的录入
#include <ncurses.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
typedef struct book
{
char name[10];
char author[10];
float score;
}Book;
void input(Book *b,int count);
void init();
void destory();
int main()
{
int fd;
struct stat *st; //存放文件信息
Book *b; //用于接受虚拟映射的地址
int size = sizeof(Book); //一条信息的大小
int count; //用来记录有几条信息
init();
fd = open("home.dat",O_RDWR|O_CREAT,0666);
if(fd==-1)
{
fd = open("home.dat",O_RDWR);
if(fd==-1)
{
printf("Open erroe%m\n");
exit(-1);
}
}
fstat(fd,st);
count = (st->st_size)/size;
ftruncate(fd,(st->st_size)+size);
b = mmap(0,(st->st_size)+size,PROT_WRITE,MAP_SHARED,fd,0);
input(b,count);
munmap(b,(st->st_size)+size);
close(fd);
destory();
return 0;
}
void destory()
{
endwin();
}
void init()
{
initscr();
box(stdscr,0,0);
}
void input(Book *b,int count)
{
mvaddstr(10,10,"Enter the name of book[ ]");
mvgetnstr(10,34,b[count].name,10);
mvaddstr(12,10,"Enter the name of author[ ]");
mvgetnstr(12,36,b[count].author,10);
mvaddstr(14,10,"Enter the price of book[ ]");
mvscanw(14,35,"%f",&(b[count].score));
}
执行:gcc home.c -lcurses -omain
结果是:Segmentation fault (core dumped) 展开
#include <ncurses.h>
#include <sys/mman.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
typedef struct book
{
char name[10];
char author[10];
float score;
}Book;
void input(Book *b,int count);
void init();
void destory();
int main()
{
int fd;
struct stat *st; //存放文件信息
Book *b; //用于接受虚拟映射的地址
int size = sizeof(Book); //一条信息的大小
int count; //用来记录有几条信息
init();
fd = open("home.dat",O_RDWR|O_CREAT,0666);
if(fd==-1)
{
fd = open("home.dat",O_RDWR);
if(fd==-1)
{
printf("Open erroe%m\n");
exit(-1);
}
}
fstat(fd,st);
count = (st->st_size)/size;
ftruncate(fd,(st->st_size)+size);
b = mmap(0,(st->st_size)+size,PROT_WRITE,MAP_SHARED,fd,0);
input(b,count);
munmap(b,(st->st_size)+size);
close(fd);
destory();
return 0;
}
void destory()
{
endwin();
}
void init()
{
initscr();
box(stdscr,0,0);
}
void input(Book *b,int count)
{
mvaddstr(10,10,"Enter the name of book[ ]");
mvgetnstr(10,34,b[count].name,10);
mvaddstr(12,10,"Enter the name of author[ ]");
mvgetnstr(12,36,b[count].author,10);
mvaddstr(14,10,"Enter the price of book[ ]");
mvscanw(14,35,"%f",&(b[count].score));
}
执行:gcc home.c -lcurses -omain
结果是:Segmentation fault (core dumped) 展开
1个回答
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询